Reputation: 992
Is there a built-in method to find the next greatest double number in Java?
When writing a test, I sometimes want to verify that an operation succeeds for x
but fails for values greater than x
. One way to do this is to show that the operations fails for x + eps
. But eps
must be chosen taking into account the value of x
to avoid problems like 180 + 1e-15 == 180
.
To automatically select eps
, I'd like to find the smallest representable number greater than x
. I was surprised that I didn't find a standard library method, so I wrote the following:
public static double nextDouble(double d) {
if (d < 0) {
return -prevDouble(Math.abs(d));
} else {
return Double.longBitsToDouble(Double.doubleToLongBits(d) + 1);
}
}
public static double prevDouble(double d) {
if (d < 0) {
return -nextDouble(-d);
} else {
return Double.longBitsToDouble(Double.doubleToLongBits(d) - 1);
}
}
Should I use these custom functions, or is there a built-in approach available?
Upvotes: 3
Views: 150
Reputation: 178253
There is the Math.nextUp
method.
Returns the floating-point value adjacent to d in the direction of positive infinity.
There are overloads to take double
and float
. There are also corresponding Math.nextDown
methods.
Upvotes: 7