Presentation is loading. Please wait.

Presentation is loading. Please wait.

The Math class Java provides certain math functions for us. The Math class contains methods and constants that can be very useful. The Math class is like.

Similar presentations


Presentation on theme: "The Math class Java provides certain math functions for us. The Math class contains methods and constants that can be very useful. The Math class is like."— Presentation transcript:

1 the Math class Java provides certain math functions for us. The Math class contains methods and constants that can be very useful. The Math class is like the String class; it is used so often that it is automatically imported.

2 AP methods in Math class MethodReturn typeReturns Math.sqrt(x)doublesquare root of x (>=0) Math.pow(x,y)doublexyxy Math.abs(x)double or intabsolute value of x Math.random()doublereturns a random value >= 0 and < 1 Useful variables in Math class Math.PI double gives a close approx to pi OTHERS ARE FOUND AT THE API HERE

3 Static methods The Math class contains static methods and static fields. This means that the method does not operate on a particular object. You do not instantiate an object of the Math class in order to use the methods of the Math class. You invoke the square root method by –Math.sqrt(4)

4 Example public static void main(String[] args) { System.out.println(Math.sqrt(16)); System.out.println(Math.random()); System.out.println((int)(Math.random()*3+1)); System.out.println(Math.abs(-5.1)); System.out.println(Math.abs(-5)); System.out.println(Math.pow(2,5)); } 4.0 0.7872152671821442 1 5.1 5 32.0

5 Example public class Circle { // Other code goes here // Returns the circumference of the Circle public double findCircumference() { return Math.PI * diameter; } // Returns the area of the Circle public double findArea() { double radius = diamter/2; return Math.PI * Math.pow(radius,2); } }

6 Math.random() The method Math.random() is really useful. Recall it returns a double from 0.0 to 1.0 (but not including 1.0) So values we might get could be:.342519638....00043242....956832443... A clever way to find a random integer between 0 and 5 inclusive we could multiply by 6 and find the integer value of that number. int randomFrom0To5= (int)(Math.random()*6); If we wanted a random value from 1 to 52, we could do much the same, multiply by 52 (this would give us values from 0 to 51.9999. If we took the (int) of that we would get values from 0 to 51. We then would have to add 1 to that. int randomFrom1To52= (int)(Math.random()*52) + 1;


Download ppt "The Math class Java provides certain math functions for us. The Math class contains methods and constants that can be very useful. The Math class is like."

Similar presentations


Ads by Google