or use r = r * (longBits < 0)? -1: 1; which should be compiled to a conditional move.
cheers, Rémi ----- Mail original ----- > De: "Jeff Hain" <jeffh...@rocketmail.com> > À: core-libs-dev@openjdk.java.net > Envoyé: Dimanche 5 Juin 2016 20:17:49 > Objet: Math.round optimization, and round to int > > 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 > >