Search code examples
floating-pointdoubleprecisionieee-754

Next higher/lower IEEE double precision number


I am doing high precision scientific computations. In looking for the best representation of various effects, I keep coming up with reasons to want to get the next higher (or lower) double precision number available. Essentially, what I want to do is add one to the least significant bit in the internal representation of a double.

The difficulty is that the IEEE format is not totally uniform. If one were to use low-level code and actually add one to the least significant bit, the resulting format might not be the next available double. It might, for instance, be a special case number such as PositiveInfinity or NaN. There are also the sub-normal values, which I don't claim to understand, but which seem to have specific bit patterns different from the "normal" pattern.

An "epsilon" value is available, but I have never understood its definition. Since double values are not evenly spaced, no single value can be added to a double to result in the next higher value.

I really don't understand why IEEE hasn't specified a function to get the next higher or lower value. I can't be the only one who needs it.

Is there a way to get the next value (without some sort of a loop which tries to add smaller and smaller values).


Solution

  • C# now has the System.Math.BitIncrement/BitDecrement functions as of .Net Core 3.0+.

    According to Microsoft's notes:

    [These correspond] to the nextUp and nextDown IEEE operations. They return the smallest floating-point number that compares greater or lesser than the input (respectively). For example, Math.BitIncrement(0.0) would return double.Epsilon.