Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The difference between Math.floorMod() and % in java

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

like image 421
Huili Lin Avatar asked Sep 18 '18 00:09

Huili Lin


People also ask

What are the Math function in Java?

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.

Is Math a standard class in Java?

Yes, Math is a standard Java class.

How does modulus work in Java?

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.

Is Math built into Java?

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.


1 Answers

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
like image 84
Scary Wombat Avatar answered Oct 12 '22 03:10

Scary Wombat