Java math
›Short versionOpen if you only have a minute.
- Math methods are called on the class: Math.max(a, b). You do not construct a Math object.
- Integer division still happens in your expression. Math cannot restore a fraction that / already dropped.
- A cast truncates toward zero. Math.round goes to the nearest integer. floor and ceil go in fixed directions.
- Math.random() is from 0.0 up to but not including 1.0. (int) (Math.random() * 10) is 0 through 9.
- Math.abs(Integer.MIN_VALUE) stays negative. That positive value does not fit in an int.
covers the calculations that are awkward to write with + and / alone: the larger of two numbers, a square root, an absolute value, a power. It does not replace . That rule still belongs to the expression you write before the call.
System.out.println(Math.max(5, 10));
System.out.println(Math.min(5, 10));
System.out.println(Math.sqrt(64));
System.out.println(Math.abs(-4.7));
System.out.println(Math.pow(2, 3));What the console shows
10 5 8.0 4.7 8.0
sqrt, abs of a double, and pow return doubles, which is why those three lines show a decimal. Math.sqrt(-1) returns NaN, not an exception. A later comparison with NaN is never true, including NaN == NaN, so a bad root can slip through an if.
Rounding is a choice of direction
methods exist because a cast will not do this job. Decide which way a fraction should move, then call that method.
double price = 19.99;
System.out.println((int) price);
System.out.println(Math.round(price));
System.out.println(Math.floor(price));
System.out.println(Math.ceil(price));The lines print 19, then 20, then 19.0, then 20.0. floor and ceil return doubles. round on a double returns a long. On a negative number the directions split further: Math.floor(-1.2) is -2.0, and (int) -1.2 is -1.
A random double, and the int you meant
is the small source of unpredictable doubles. The range is half-open, and a cast truncates, so the integer formula is mostly about the parentheses and the last value you are willing to exclude.
double unit = Math.random();
int fromZero = (int) (Math.random() * 10);
int fromOne = (int) (Math.random() * 10) + 1;unit is at least 0.0 and less than 1.0. fromZero is an int from 0 through 9. fromOne is an int from 1 through 10. (int) Math.random() * 10 is always 0: the cast binds tighter than the multiplication, Math.random() becomes 0, and zero times ten is zero.
The same class offers Math.PI and the log and trig methods, all in radians where an angle is involved. None of them change the fact that 10 / 3 is 3. That decision sits with the operators.
What integers can (int) (Math.random() * 10) produce? Why does (int) Math.random() * 10 produce only one of them?
The parenthesized form produces 0, 1, 2, 3, 4, 5, 6, 7, 8, or 9. It never produces 10, because Math.random() * 10 is always below 10 and the cast drops the fraction. Without the parentheses the cast runs first, every value below 1 becomes 0, and 0 times 10 is 0.