Get next smallest Double number

前端 未结 2 2119
借酒劲吻你
借酒劲吻你 2020-12-07 00:31

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-smalles

2条回答
  •  佛祖请我去吃肉
    2020-12-07 01:14

    If your numbers are finite, you can use a couple of convenient methods in the BitConverter class:

    long bits = BitConverter.DoubleToInt64Bits(value);
    if (value > 0)
        return BitConverter.Int64BitsToDouble(bits - 1);
    else if (value < 0)
        return BitConverter.Int64BitsToDouble(bits + 1);
    else
        return -double.Epsilon;
    

    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.

提交回复
热议问题