How to get the minimum next or previous possible double value supported by architecture?

Suppose I have a double d variable. Is there a way to get the next or previous value that is supported by the CPU architecture.

As a trivial example, if the value was 10.1245125, and the accuracy of the architecture was fixed at 7 decimal places, then the next value would be 10.1245126, and the previous value would be 10.1245124.

Obviously, this is not so easy for floating point architecture. How can I achieve this (in Java)?

+6
source share
1 answer

In fact, the IEEE 754 floating point architecture simplifies: thanks to the standard, the function is called nextafter in almost all languages ​​that support it, and this uniformity allowed me to write the answer to your question with very little familiarity with Java:

java.lang.Math.nextAfter(double start, double direction) returns a 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 for specifying the direction (second argument). Do not make a general mistake when writing something like Math.nextAfter(x, x+1) , which only works as long as 1 is greater than ULP x .

Anyone who writes above most likely means Math.nextAfter(x, Double.POSITIVE_INFINITY) , which saves addition and works for all x values.

+11
source

Source: https://habr.com/ru/post/981457/


All Articles