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)?
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.
The value of this constant is negative 1.7976931348623157E+308. The result of an operation that is less than Double. MinValue is 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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With