Code review request: 6282196 There should be Math.mod(number, modulo) methods (original) (raw)

Stephen Colebourne scolebourne at joda.org
Wed Feb 22 16:49:03 UTC 2012


Thanks for the explanation, I don't think that the change in floorDiv behaviour will cause JSR-310 a problem Stephen

On 22 February 2012 16:21, Roger Riggs <Roger.Riggs at oracle.com> wrote:

On 02/22/2012 09:37 AM, Stephen Colebourne wrote: Can you explain why the mod implementation differs from that in JSR-310? https://github.com/ThreeTen/threeten/blob/master/src/main/java/javax/time/MathUtils.java#L401 The code ((a % b) + b) % b; is short and involves no branches, which should aid performance and inlining. Is this to do with accepting a negative second argument? Performance testing? For floorMod, the numeric results are the same but the performance is slightly better. The performance difference is very noticeable for long's, using a single divide and a multiply with the branch is about 1.5 times as fast as the alternative using two % operations. For int's the difference was minimal but still faster.  I did not compare against floating point divide. Since it depends on the performance of the divide instruction it will be sensitive to specific processors. For interpreters and devices without floating point hardware (yes they exist) and slower hardware minimizing the number of divides makes sense. I would rather not try to tune for specific hardware and leave that to the VM.

I'd like to see performance numbers comparing the two approaches, as JSR-310 might need to continue using the double % version if it is faster. Similarly, the proposed floorDiv requires evaluation of the complex if statement every time, whereas the JSR-310 one only requires an if check against zero. Whats the rationale for the difference, which is intuitively (non-proven) slower., For floorDiv, the results are different when the sign of the divisor is negative. Using the definition of the largest integer less than the quotient with the arguments (4, -3) should be -1.3333, the largest integer less than that is -2. The JSR 310 expression   (a/v) evaluates to -1. I choose to be consistent with the Math.floor behavior. Roger

thanks Stephen On 22 February 2012 14:24, Roger Riggs <Roger.Riggs at oracle.com> wrote: Hi, 6282196 There should be Math.mod(number, modulo) methods <http://bugs.sun.com/bugdatabase/viewbug.do?bugid=6282196> Requests that floor and modulus methods be provided for primitive types. Floor division is pretty straight-forward, rounding toward minus infinity. For modulus of int and long, the sign and range follow  the exiting floor method in java.util.Math and satisfy the relation that mod(x, y) = (x - floorDiv(x, y) * y). Please review and comment,  http://cr.openjdk.java.net/~rriggs/6282196.1/ Thanks, Roger



More information about the core-libs-dev mailing list