As part of a unit test, I need to test some boundary conditions. One method accepts a System.Double
argument.
Is there a way to get the next-smallest double value? (i.e. decrement the mantissa by 1 unit-value)?
I considered using Double.Epsilon
but this is unreliable as it's only the smallest delta from zero, and so doesn't work for larger values (i.e. 9999999999 - Double.Epsilon == 9999999999
).
So what is the algorithm or code needed such that:
NextSmallest(Double d) < d
...is always true.
The Wikipedia page on double-precision floating point is here: http://en.wikipedia.org/wiki/Double_precision_floating-point_format
For fun I wrote some code to break out the binary representation of the
double
format, decrements the mantissa and recomposes the resultant double. Because of the implicit bit in the mantissa we have to check for it and modify the exponent accordingly, and it might fail near the limits.Here's the code:
All of which gives you a value that is different from the initial value by a change in the lowest bit of the mantissa... in theory :)
Here's a test:
Gives the following results on my PC:
The difference is there, but is probably below the rounding threshold. The expression
test == prev
evaluates to false though, and there is an actual difference as shown above :)If your numbers are finite, you can use a couple of convenient methods in the
BitConverter
class:IEEE-754 formats were designed so that the bits that make up the exponent and mantissa together form an integer that has the same ordering as the floating-point numbers. So, to get the largest smaller number, you can subtract one from this number if the value is positive, and you can add one if the value is negative.
The key reason why this works is that the leading bit of the mantissa is not stored. If your mantissa is all zeros, then your number is a power of two. If you subtract 1 from the exponent/mantissa combination, you get all ones and you'll have to borrow from the exponent bits. In other words: you have to decrement the exponent, which is exactly what we want.