简体   繁体   English

获得(非零)double或float的最小步长

[英]Obtaining the smallest step size for a (non-zero) double or float

For the purposes of boundary value analysis in testing, I've been looking to get the smallest step sizes for doubles or floats in .Net. 出于测试中边界值分析的目的,我一直希望在.Net中获得最小的步长。 This will allow me to get the next larger and next smaller value that can be represented in a double or float. 这将允许我获得下一个较大和下一个较小的值,可以用double或float表示。

double.epsilon , "applies only to Double instances that have a value of zero or an exponent of -1022". double.epsilon ,“仅适用于值为零或指数为-1022的Double实例”。

Let's say that I have an arbitrary double or float. 假设我有一个任意的double或float。 What are the next larger and next smaller value that I can represent in .Net? 我可以在.Net中表示的下一个较大和下一个较小的值是什么?

Based on the MSDN article, I have implemented the following code, which looks plausible: 根据MSDN文章,我实现了以下似乎合理的代码:

private static int GetExponentWithMinorAdjustment(double value)
{
    //int indent = result.Length;

    // Convert the double to an 8-byte array.
    byte[] bytes = BitConverter.GetBytes(value);

    int exponent = (bytes[7] & 0x07F) << 4;
    exponent = exponent | ((bytes[6] & 0xF0) >> 4);
    int adjustment = exponent != 0 ? 1023 : 1022;

    return exponent != 0 ? exponent - 1 : exponent; ;
}

private static double NextLargerNumber(double value)
{
    // Cannot use double.epsilon * Math.Pow(2, GetExponentWithMinorAdjustment(value)) as this results in infinity
    return value + Math.Pow(2, GetExponentWithMinorAdjustment(value) - 1074));
}

The problem with the above code is that it looks shaky. 上面的代码的问题在于它看起来不稳定。 Notice the ternary operator (inspired from the MSDN article); 注意三元运算符(来自MSDN文章); what's the purpose of that adjustment? 调整的目的是什么?

Also, while the output of several tests looks OK for positive double values, the results for negative values do not seem as good (see output image): 同样,虽然对于正整数值,几个测试的输出看起来都可以,但是负值的结果看起来并不好(请参见输出图像): 节目输出

What would an acceptable, correct and ideal solution to this problem look like? 这个问题的可接受,正确和理想的解决方案是什么样的?

Use unsafe code to map the bits directly to an unsigned int, increment or decrement, convert back. 使用不安全的代码将位直接映射到无符号的int,递增或递减,转换回去。

Might require additional special handling at the boundaries of 0 and the special values for infinity, Nan and so on. 可能需要在0的边界以及无穷大,Nan等的特殊值处进行额外的特殊处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM