Java Math Class. What is the Math Class? The Math Class is another class that is prepared by Java for us to use We use this class for mathematical operations.

Slides:



Advertisements
Similar presentations
Escape Sequences \n newline \t tab \b backspace \r carriage return
Advertisements

1001ICT Programming 1 Semester 1, 2011 Lecture 6 Using Java Classes (Textbook, Chapter 3, Sections 3.2 to 3.7 ONLY)
Chapter 6: User-Defined Functions I
Basic Java Constructs and Data Types – Nuts and Bolts
Introduction to C Programming
Introduction to Programming Java Lab 1: My First Program 11 January JavaLab1.ppt Ping Brennan
Introduction to Programming Java Lab 3: Variables and Number types 25 January JavaLab3.ppt Ping Brennan
Lecture 10 Methods COMP1681 / SE15 Introduction to Programming.
Methods and Formatted Output Chapter 4. Overview Breaking down a big program into small methods. Formatting output – using printf – using DecimalFormat.
The ArrayList Class and the enum Keyword
1 public class Newton { public static double sqrt(double c) { double epsilon = 1E-15; if (c < 0) return Double.NaN; double t = c; while (Math.abs(t - c/t)
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
1 Review Quisioner Kendala: Kurang paham materi. Praktikum Pengaruh teman.
Introduction to Java Applications
© 2007 Lawrenceville Press Slide 1 Chapter 5 The if Statement  Conditional control structure, also called a decision structure  Executes a set of statements.
Computer Programming Lab(7).
Introduction to Programming G51PRG University of Nottingham Revision 1
Lecture 8 Instructor: Craig Duckett. Assignments TONIGHT Lecture 8 Assignment 2 Due TONIGHT Lecture 8 by midnight Monday, February 2 nd Lecture 10 Assignment.
Lecture 12 Recursion part 1
Building Java Programs
1 MATH METHODS THAT RETURN VALUES. 2 JAVA'S MATH CLASS.
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Return values.
Self Check 1.Which are the most commonly used number types in Java? 2.Suppose x is a double. When does the cast (long) x yield a different result from.
Procedural programming in Java
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
10-Jun-15 Introduction to Primitives. 2 Overview Today we will discuss: The eight primitive types, especially int and double Declaring the types of variables.
Introduction to Primitives. Overview Today we will discuss: –The eight primitive types, especially int and double –Declaring the types of variables –Operations.
Chapter 6: User-Defined Functions I
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs with Scanner.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
Random (1) Random class contains a method to generate random numbers of integer and double type Note: before using Random class, you should add following.
CS180 Recitation 3. Lecture: Overflow byte b; b = 127; b += 1; System.out.println("b is" + b); b is -128 byte b; b = 128; //will not compile! b went out.
Chapter 6: User-Defined Functions I
The printf Method The printf method is another way to format output. It is based on the printf function of the C language. System.out.printf(,,,..., );
Chapter 2 Screen Output Section 2.1 Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Week #2 Java Programming. Enable Line Numbering in Eclipse Open Eclipse, then go to: Window -> Preferences -> General -> Editors -> Text Editors -> Check.
11 Chapter 3 DECISION STRUCTURES CONT’D. 22 FORMATTING FLOATING-POINT VALUES WITH THE DecimalFormat CLASS We can use the DecimalFormat class to control.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
Variable Declaration  It is possible to declare multiple variables of the same data type on the same line.  Ex. double hours, rate, total;  Variables.
Lecture 2: Static Methods, if statements, homework uploader.
* * 0 Chapter 6 Java Methods. * * 0 Method Syntax [access specifier][qualifier] return type method name(argument list) Access specifier public – method.
Formatting Screen Output How do I make my numbers look pretty?
Week 2 - Friday.  What did we talk about last time?  Using Scanner to get input  Basic math operations.
University of Palestine software engineering department Introduction to data structures Control Statements: Part 1 instructor: Tasneem Darwish.
USER-DEFINED FUNCTIONS. STANDARD (PREDEFINED) FUNCTIONS  In college algebra a function is defined as a rule or correspondence between values called the.
Mathematical Calculations in Java Mrs. G. Chapman.
The String Class A String is an object. An object is defined by a class. In general, we instantiate a class like this: String myString = new String(“Crazy.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Introduction As programmers, we don’t want to have to implement functions for every possible task we encounter. The Standard C library contains functions.
Module-E- Libraries1/49 Module E- Standard Libraries Input and Validation Formatted Output Library Functions.
Sections 5.1 – 5.4 © Copyright by Pearson Education, Inc. All Rights Reserved.
Mathematical Calculations in Java Mrs. C. Furman.
The Math Class Methods Utilizing the Important Math Operations of Java!
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Creating and Using Class Methods. Definition Class Object.
COMPUTER PROGRAMMING I Objective 7.04 Apply Built-in Math Class Functions.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
+ Note On the Use of Different Data Types Use the data type that conserves memory and still accomplishes the desired purpose. For example, depending on.
Chapter 6: User-Defined Functions I
© 2016 Pearson Education, Ltd. All rights reserved.
User-Defined Functions
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Chapter 6: User-Defined Functions I
CS 1054 Introduction to Programming in Java
Presentation transcript:

Java Math Class

What is the Math Class? The Math Class is another class that is prepared by Java for us to use We use this class for mathematical operations The Math Class contains many different complex mathematical functions

Do you remember? When we used the external class Scanner we had to use; To make use of the Math class, this is not needed. It is automatically imported Import Java.util.*;

How to use the Math Class You must include the class name Math each time you wish to use the Math Class Example; System.out.println(Math.pow(2,8)); Indicating you wish to output something Calling the Math Class Calling the function power Arguments (will work out 2 8 )

What happens… In the code above the function power is being used The arguments being used are 2 and 8 The program should output 256 Why? 2 8 = 256 System.out.println(Math.pow(2,8));

Problem? By using the code above the result of 256 is not being saved anywhere as it is just simply an output To save the result we need to use the following code System.out.println(Math.pow(2,8)); double result = Math.pow(2,8); System.out.println(result);

Fed up of writing Math … Programmers are lazy and do not enjoy writing the same things a number of times We could use a java statement to avoid this, this is known as a static import statement (always placed before we create a class) import static.java.lang.Math.*;

… Once we use the static import statement the code to use the power function would be much shorter. The Math keyword no longer needs to be used double result = pow(2,8);

Math Class Functions 1. Math.pow() – To the power of 2. Math.sqrt() – The square root 3. Math.abs() – Outputs only positive numbers 4. Math.random() – Outputs a random number 5. Math.round() – Rounds up numbers 6. Math.ceil() – Outputs the smallest number 7. Math.floor() – Outputs the largest number

Math.pow() The Math.pow() works out the power of a certain number. For example if we wish to find the answer of 2 9 we would use the following code

import static java.lang.Math.*; class Power { public static void main (String args[]){ int a = 2; int b = 9; double p = pow(a,b); System.out.println(p); }

Math.sqrt() The Math.sqrt() function is used when we want to find the square root of a number For example we want to find the square root of 100 and 10000

import static java.lang.Math.*; class SquareRoot { public static void main (String args[]){ int a = 100; int b = 10000; double sr1 = sqrt(a); double sr2 = sqrt(b); System.out.println("The square root of 100 is " + sr1 + "\nThe square root of is " + sr2); }

Math.abs() The Math.abs() function gives the absolute value of the number The absolute value of a number is equal to the same number without the sign. It is useful on calculations which require positive numbers only We would use Math.abs() to find the square root of a negative number (which cannot be done), so first we find out the absolute value.

import static java.lang.Math.*; class SquareRoot { public static void main (String args[]){ double a = -20.2; double positive = abs(a); System.out.println(positive); }

ACTIVITY Using the Math functions we have leant so far Create a program that will find; Square root -90

Math.random() This functions outputs a random number from a given group of numbers This could be used in many games as a dice The random function works with double data type only hence we would need to typecast this into a int not to get decimal numbers.

… The random function also outputs 0 as a random number, if you wouldn’t like this to happen you must use the +1 function For example you want to represent a dice so you only want numbers from 1 to 6 int dice = (int)(Math.random()*6)+1;

import static java.lang.Math.*; class RandomDice{ public static void main(String args[]){ int dice = (int)(random()*6)+1; System.out.println("Player one roll "+ dice); }

ACTIVITY Using the Math functions we have leant so far Coin Toss Assume that; 1.Heads = 1 2.Tails = 2 Write a program that generates a random number between 1 and 2 to represent heads and tails

Math.round() The Math.round() function results in the closest value to the integer If the fraction value is 1.7, it will add 1 to 7 and output 8 Basically the Math.round() function would output the whole number with no decimal

import static java.lang.Math.*; class round{ public static void main(String args[]){ double num1 = round( ); double num2 = round(34.88); System.out.println(num1 + "\n" + num2); }

Math.ceil() The Math.ceil() also outputs decimal numbers as whole numbers This is done in a different way as it will return the smallest whole number which is not less than the number given For example; ◦ 13.3 would result in 14 ◦ would result in -11

import static java.lang.Math.*; class ceil{ public static void main(String args[]){ double num1 = ceil(10.1); double num2 = ceil(-43.4); System.out.println(num1 + "\n" + num2); }

Math.floor() The Math.floor() does the exact opposite to Math.ceil() The whole number would be the next largest number possible For example; ◦ 13.3 would result in 13 ◦ would result in -12

import static java.lang.Math.*; class floor{ public static void main(String args[]){ double num1 = floor(10.1); double num2 = floor(-43.4); System.out.println(num1 + "\n" + num2); }

Formatting values Number of decimal places to be printed

Output of Results So far we should know how to use; 1.print() 2.println() Now we will be using printf() which is used to determine how many decimal places we would like our result to have

Placeholders The following are the placeholders we will be using %f only PlaceholderUsed for %d int, byte, short, long %ffloat %sString %cchar

Decimal Places When using %f the number of decimal places can be specified What happens? 1.%.2f = determines that you want 2 decimal places (replaces the actual answer) 2.\n is used to display the actual answer on the “next line” double num1 = ; double num2 = ; double ans = num1+num2; System.out.printf(“Formatted to 2 decimal places :%.2f\n”,ans);

import static java.lang.Math.*; class PrintFDemo { public static void main (String args[]) { double num1 = ; double num2 = ; double ans = num1+num2; System.out.printf("Formatted to 2 decimal places :%.2f\n",ans); }

Field Size A field can also be used to hold a specific number. This means how many characters are to be held For example we want to have a field size of 8 this mean only 20 numbers can be held double num1 = ; double num2 = ; double ans = num1+num2; System.out.printf(“Formatted to field size 20:%20.3f\n”,ans);

import static java.lang.Math.*; class feild { public static void main (String args[]) { double num1 = ; double num2 = ; double ans = num1+num2; System.out.printf("Formatted to 3 decimal places and a field size of 20 :%20.3f\n",ans); }

Padding with 0s From the output above we would see that there are many empty spaces before the number in order to use the 20 field spaces We might wish to pad (fill) these spaces with 0s all you have to do is add a 0 in front of your placeholder double num1 = ; double num2 = ; double ans = num1+num2; System.out.printf(“Formatted to field size 20:%020.3f\n”,ans);

import static java.lang.Math.*; class feild { public static void main (String args[]) { double num1 = ; double num2 = ; double ans = num1+num2; System.out.printf("Formatted to 3 decimal places and a field size of 20 :%020.3f\n",ans); }