Math.round optimization, and round to int

Jeff Hain jeffhain at rocketmail.com
Sun Jun 5 18:17:49 UTC 2016


Hi.



While playing around with Math.round(double) code,
I found out that

if (longBits < 0) {
    r = -r;
}

can be replaced with:

long bitsSignum = (((longBits >> 63) << 1) + 1); // 2*0+1 = 1, or 2*-1+1 = -1
r *= bitsSignum;

which seems a bit faster, as one could expect due to less branching.



NB: The playing was making an "int roundToInt(double)" method.
I think it would be good to have such a method in Math
(and also versions for short/byte?),
because people often use "(int) Math.round(foo)" for this use case,
which doesn't work when out of int range.
Moreover, people should rarely catch the bug in their tests,
since they usually don't test with pathological values.

Recent example:
http://alvinalexander.com/java/how-to-round-float-double-to-int-integer-in-java



-Jeff



More information about the core-libs-dev mailing list