That is easy. Positive double's are ordered at bit level just the way longs are. So converting it to a long and increasing it and then back to a double does the trick:
public static double nextDouble(double d)
{
if (d != d) return d;
if (d == Double.MAX_VALUE) return Double.POSITIVE_INFINITY;
if (d == Double.NEGATIVE_INFINITY) return d;
if (d == Double.POSITIVE_INFINITY) return d;
d += 0.0;
int dir = d < 0.0 ? -1 : 1;
return Double.longBitsToDouble(Double.doubleToLongBits(d) + dir);
}
The same works for negative values. If you want to get the closest double that is bigger, then decrease the long representation.
In response to the alternative Math.nextUp()
, here is the source code for that method:
public static double nextUp(double d) {
if( isNaN(d) || d == Double.POSITIVE_INFINITY)
return d;
else {
d += 0.0d;
return Double.longBitsToDouble(Double.doubleToRawLongBits(d) +
((d >= 0.0d)?+1L:-1L));
}
}
This is equivalent with my code, that does the extra checks for infinity.