After spending a little bit of time studying methods offered by standard java.lang.Math class I stumbled upon two methods that in combination would allow me to round values up to a power of two.

double Math.scalb(double value) - multiplies given double value by the given power of two,

double Math.iround(double value) - discards everything to the right of the decimal point.

So here's what needs to be done:

- Divide the given double value by the given power of two.
- Discard the decimal part.
- Multiply the result by the given power of two.

Here's the method:

public static double round(double value, int power) { // Divide value by 2^power double scaled = Math.scalb(value, -power); // Discard the fractional part, multiply back by 2^power return Math.scalb(Math.rint(scaled), power); }This approach is great when you compare Doubles with tolerance and need equal hash codes for

*equal*values.

Don't forget that rounding is done up to a certain power of two:

Powers of two. | Values that the fractional part may assume. |

-1 | 0.5 |

-2 | 0.25, 0.5, 0.75 |

-3 | 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875 |

## No comments:

Post a Comment