c - 查找不能表示为 IEEE-754 32 位 float 的最小整数

标签 c floating-point floating-accuracy

<分区>

Possible Duplicate:
Which is the first integer that an IEEE 754 float is incapable of representing exactly?

首先,这是一个家庭作业问题,只是为了立即解决这个问题。当然,我不是在寻找一个勺子喂养的解决方案,只是可能指向正确方向的一点点指示。

因此,我的任务是找到不能表示为 IEEE-754 float (32 位)的最小正整数。我知道像“5 == 5.00000000001”这样的相等性测试会失败,所以我想我会简单地遍历所有数字并以这种方式测试它:

int main(int argc, char **argv)
{
    unsigned int i; /* Loop counter. No need to inizialize here. */

    /* Header output */
    printf("IEEE floating point rounding failure detection\n\n");

    /* Main program processing */
    /* Loop over every integer number */
    for (i = 0;; ++i)
    {
        float result = (float)i;

        /* TODO: Break condition for integer wrapping */

        /* Test integer representation against the IEEE-754 representation */
        if (result != i)
            break; /* Break the loop here */
    }

    /* Result output */
    printf("The smallest integer that can not be precisely represented as IEEE-754"
           " is:\n\t%d", i);


    return 0;
}

这失败了。然后我尝试从 float “结果”中减去整数“i”,即“i”,希望得到我可以尝试检测的“0.000000002”,但也失败了。

谁能指出我可以依赖的浮点属性来获得所需的中断条件?

-------------------- 下面更新----------------

感谢您在这方面的帮助!我在这里学到了很多东西:

  1. 我最初的想法确实是正确的,并确定了它打算在其上运行的机器(Solaris 10、32 位)上的结果,但无法在我的 Linux 系统(64 位和 32 位)上运行。

  2. Hans Passant 添加的更改使该程序也适用于我的系统,这里似乎出现了一些我没有预料到的平台差异,

谢谢大家!

最佳答案

问题在于您的相等性测试是浮点测试。 i 变量将首先转换为 float ,当然会生成相同的 float 。将 float 转换回 int 以获得整数相等性测试:

float result = (float)i;
int truncated = (int)result;
if (truncated != i) break;

如果它以数字 16 开头,那么您找到了正确的那个。将其转换为十六进制并解释为什么它未能获得等级奖励。

关于c - 查找不能表示为 IEEE-754 32 位 float 的最小整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3890123/

相关文章:

iphone - 什么是好的c编译器

random - 接近零的均匀真实分布

math - float 学坏了吗?

python - 垫 python float

math - float 学坏了吗?

floating-point - 您如何处理 GLSL 中增加浮点值的小数精度?

c - 用 C 中充满数字的 char 数组填充 int 数组(char 数组到 int 数组)

C: char 到 int 的转换

c - 错误: ld returned 1 exit status at C

c++ - 在 C++ 中将 4 个字节转换为 float 的最快方法