5

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

  • Check this out: http://stackoverflow.com/questions/1971645/is-math-ieeeremainderx-y-equivalent-to-xy – Jose Antonio Nov 03 '11 at 16:23
  • Check out the [relevant JLS section](http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.17.3) where it is defined. – user207421 Dec 21 '14 at 02:29

2 Answers2

10

Apart from the type difference already pointed out by John B, there's a significant difference in semantics, too. Math.IEEEremainder(x, y) returns x - n * y where n is the closest integer to x / y (taking the even integer in the case of a tie), while x % y returns x - n * y where n is the integer part of x / y (i.e., n is the result of rounding the true value of x / y towards zero, instead of towards nearest).

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

Here's the official documentation for Math.IEEEremainder.

Mark Dickinson
  • 29,088
  • 9
  • 83
  • 120
1

Math.IEEEremainder accepts and returns doubles and should therefore be used when you want a double result. If you want the modulus, use % as it gives an int and would be more efficient than double arithmetic.

John B
  • 32,493
  • 6
  • 77
  • 98
  • The result of % between two floating-point values cannot possibly be an `int`, as [NaN is one of the possible results](http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.17.3). – user207421 Dec 21 '14 at 02:27