Difference in Java, if any, between the% operator and the IEEEremainder () method?

In Java, is there any functional or performance difference between using the% operator to get the remainder of the x / y integer division and the Math.IEEEremainder (x, y) method?

+4
source share
2 answers

In addition to the difference in type already mentioned by John B, there is a significant difference in semantics. Math.IEEEremainder(x, y) returns x - n * y , where n is the closest integer to x x / y (taking an even integer in the case of tie), and x % y returns x - n * y , where n is the integer part x / y (i.e., n is the result of rounding the true value of x / y to zero, and not to the nearest one).

To illustrate the difference: Math.IEEEremainder(9.0, 5.0) will be -1.0 , since the closest number to 9.0 / 5.0 is 2 , and 9.0 - 2 * 5.0 - -1.0 . But 9.0 % 5.0 will be 4.0 , since the integer part 9.0 / 5.0 is 1 and 9.0 - 1 * 5.0 is 4.0 .

Here is the official documentation for Math.IEEEremainder .

+9
source

Math.IEEEremainder accepts and returns doubles and therefore should be used when you want to get a double result. If you need a module, use % as it gives an int and will be more efficient than double arithmetic.

+1
source

Source: https://habr.com/ru/post/1379507/


All Articles