Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 trivial example, if the value was 10.1245125 and the precision of the architecture was fixed to 7 decimal places, then the next value would be 10.1245126 and the previous value would be 10.1245124.

Obviously on floating-point architectures this is not that simple. How would I be able to achieve this (in Java)?

like image 721
jbx Avatar asked Jan 23 '15 14:01

jbx


People also ask

What is the smallest double in Java?

A constant holding the smallest positive nonzero value of type double , 2-1074. It is equal to the hexadecimal floating-point literal 0x0. 0000000000001P-1022 and also equal to Double.

What is the value of double min_ value?

The value of this constant is negative 1.7976931348623157E+308. The result of an operation that is less than Double. MinValue is Double.

What is the maximum value for a double?

The greatest maximum value that a double can have is 1.79769313486231570e+308d. The minimum value a double can have. The lowest minimum value that a double can have is 2.2250738585072014E-308.

What is double data type example?

Example 2: Using the scientific Manipulator. precision(5) sets the precision of the digits to 5. So, a double value of 3.1415926535 is printed in the scientific format with 5 digits after the decimal as 3.14159e+00.


1 Answers

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.

like image 169
Pascal Cuoq Avatar answered Oct 11 '22 13:10

Pascal Cuoq