could anybody tell me the difference between Math.floorMod() and % in java?
I was quite confused when
int a = 3;
int b = -2;
System.out.println(a % b);
System.out.println(Math.floorMod(a,b));
And the result is 1 -1 instead of 1 1
Java Math class provides several methods to work on math calculations like min(), max(), avg(), sin(), cos(), tan(), round(), ceil(), floor(), abs() etc. Unlike some of the StrictMath class numeric methods, all implementations of the equivalent function of Math class can't define to return the bit-for-bit same results.
Yes, Math is a standard Java class.
What is a Modulus operator in Java? The modulus operator returns the remainder of the two numbers after division. If you are provided with two numbers, say, X and Y, X is the dividend and Y is the divisor, X mod Y is there a remainder of the division of X by Y.
Java contains a set of built-in math operators for performing simple math operations on Java variables. The Java math operators are reasonably simple. Therefore Java also contains the Java Math class which contains methods for performing more advanced math calculations in Java.
As per the javadocs
If the signs of the arguments are the same, the results of floorMod and the % operator are the same.
floorMod(4, 3) == 1; and (4 % 3) == 1
If the signs of the arguments are different, the results differ from the % operator.
floorMod(+4, -3) == -2; and (+4 % -3) == +1
floorMod(-4, +3) == +2; and (-4 % +3) == -1
floorMod(-4, -3) == -1; and (-4 % -3) == -1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With