Lets say I have a double
variable d
. Is there a way to get the next or previous value that is supported by the CPU architecture.
As a triv
Actually, an IEEE 754 floating-point architecture makes this easy: thanks to the standard, the function is called nextafter in nearly all languages that support it, and this uniformity allowed me to write an answer to your question with very little familiarity with Java:
The
java.lang.Math.nextAfter(double start, double direction)
returns the floating-point number adjacent to the first argument in the direction of the second argument.
Remember that -infinity and +infinity are floating-point values, and these values are convenient to give the direction (second argument). Do not make the common mistake of writing something like Math.nextAfter(x, x+1)
, which only works as long as 1 is greater than the ULP of x
.
Anyone who writes the above probably means instead Math.nextAfter(x, Double.POSITIVE_INFINITY)
, which saves an addition and works for all values of x
.