<分区>
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”,但也失败了。
谁能指出我可以依赖的浮点属性来获得所需的中断条件?
-------------------- 下面更新----------------
感谢您在这方面的帮助!我在这里学到了很多东西:
我最初的想法确实是正确的,并确定了它打算在其上运行的机器(Solaris 10、32 位)上的结果,但无法在我的 Linux 系统(64 位和 32 位)上运行。
Hans Passant 添加的更改使该程序也适用于我的系统,这里似乎出现了一些我没有预料到的平台差异,
谢谢大家!