获取下一个最小的双号 [英] Get next smallest Double number
问题描述
作为单元测试的一部分,我需要测试一些边界条件。一种方法接受一个 System.Double
参数。
As part of a unit test, I need to test some boundary conditions. One method accepts a System.Double
argument.
有没有办法获得的下最小的双重价值? (即1个单位价值递减尾数)?
Is there a way to get the next-smallest double value? (i.e. decrement the mantissa by 1 unit-value)?
我考虑过使用 Double.Epsilon
但这是不可靠因为它仅是从零最小的增量,因此对于较大的值不工作(即 9999999999 - Double.Epsilon == 9999999999
)。
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.
推荐答案
如果你的号码是有限的,你可以用一对夫妇在 BitConverter
类方便的方法:
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格式被设计成使得构成该指数和尾数的比特一起形成一个整数具有相同的排序为浮点数。因此,要获得最大数量较少,则可以减去一个从这个号码,如果该值为正,并可以添加一个,如果该值是负的。
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.
关键之所以这样工作原理是,尾数的前导位不被存储。如果你的尾数都是零,那么你的号码是二的幂。如果从指数/尾数组合减去1,你得到所有的人,你就会有从指数位借款。换句话说:你有递减的指数,这是我们想要的东西。
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.
这篇关于获取下一个最小的双号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!