Math Library
Math Library
public static int abs ( int x) returns the absolute value of the int
value x
public static double abs ( double x) returns the absolute value of the
double value x
public static double pow ( double base, double exponent) returns a double that is the power of
the base raised to an exponent.
public static double sqrt ( double x) returns the square root value of the
double value x
public static double random () returns a random double value in the
range [0.0, 1.0) in other words 0.0
inclusive and 1.0 exclusive, or you
can say returns a double value x in
the range: 0.0 <= x < 1.0.
After this code, if base holds 2.0 and exponent holds -5.0, then result
holds the value -32.0. 2.0 to the -5th power is calculated.
After this code, if base holds 3.0 and exponent holds 4.0, then result
holds the value 81.0. 3.0 to the 4th power is calculated.
Square Root of a Number - sqrt(double x)
After this code, if z holds 2.0, then result holds the value
1.4142135623730951.
After this code, if z holds 16.0, then result holds the value 4.0.
The PI Constant of the Math class
The following code uses the square root method of the Math
class and the Math class constant PI which represents the value
3.141592653589793 to 15 decimal places.
If you knew the area of a circle, you could find the radius by
dividing the area by pi and then taking the square root of that
result. Since the sqrt() method needs one parameter of type
double, it is ok to place the expression area / math.PI in the
parenthesis. That expression will be evaluated first to one value
and that one value is the one parameter that is passed to sqrt.
It’s the 30.5 that you take to multiply times Math.random() to get
Math.random() * 30.5
You then simply add back on the 10.3 that you initially
subtracted to get …
You would add 200 to the range numbers to get the new range
of 0.0 to 400.0. Since we know the upper end is exclusive, we
just use 400.0 to multiply times Math.random() to get
Math.random() * 400.0
Note: casting has a very high priority, so Java will cast the
expression (Math.random() * 6) before it adds the 1.