Math Class Part of the Java lang package

  • Slides: 8
Download presentation
Math Class • Part of the Java. lang package. This package is from object

Math Class • Part of the Java. lang package. This package is from object so you do not have to import the lang package. • Static: Math Class is static. – This means there is only one copy. object of the class. You cannot create an • You will use the class name to call the methods.

Math Class methods • Tested on the AP • Method Summary • abs(double x)

Math Class methods • Tested on the AP • Method Summary • abs(double x) Math. abs(36. 0); Returns the absolute value of a double value. • abs(int x) Math. abs(36); • pow(double base, double exponent) Returns the value of baseexponent. • sqrt(double x) Math. pow(2, 4); Returns the absolute value of an int value. Returns the square root of a number. Math. sqrt(4);

Mathematical expressions to Java

Mathematical expressions to Java

Math. random() • The Math. random() method returns random double numbers in the range

Math. random() • The Math. random() method returns random double numbers in the range >=0. 0 to <1. 0. • • x= Math. random(); // assigns random number to x • x = 0. 0 to 0. 999999999999 • To get a desired number you multiply and cast to an int n = (int)(Math. random()* 10) This will produce a number starting at 0 inclusive and up to 10 exclusive. Number will be from 0 to 9

 • int n = (int)(Math. random()* 10) Starts at 0 and goes to

• int n = (int)(Math. random()* 10) Starts at 0 and goes to < 10. Because 0 -9 is 10 numbers. • This will produce a number starting at 0 inclusive and up to 10 exclusive. Number will be from 0 to 9

Math. random • To include the 10 You would add + 1 • int

Math. random • To include the 10 You would add + 1 • int n = (int)(Math. random()*10+1) • This will produce a number starting at 1 inclusive and up to 10 exclusive. • Number will be from 1 to 10

Math. random • Create a number starting with 20 and up to 50 not

Math. random • Create a number starting with 20 and up to 50 not including 50. The + will be the number you start with. 20 + 30 = 50 • int n = (int)(Math. random()*30 )+20; • Produce 20 to 49 29 + 20 = 49 • This will produce a number starting at 20 inclusive and up to 50 exclusive.

Generating Random Numbers Generate a number from 65 inclusive and 90 exclusive int num

Generating Random Numbers Generate a number from 65 inclusive and 90 exclusive int num = (int) (Math. random() * 25) + 65 24 + 65 = 89 65 to 89 A random decimal between 0 inclusive & 5 exclusive int num = (int)(Math. random()*5); A random integer between 10 inclusive & 45 exclusive int num = (int)(Math. random()*35); + 10 34+10 = 44 10 to 44 A random integer between 3 inclusive & 12 inclusive int num = (int)(Math. random()*10+3) 9 +3= 12 3 to 12