提问人:Fabian 提问时间:7/8/2016 最后编辑:Fabian 更新时间:7/8/2016 访问量:98
为什么浮点运算的结果取决于将一个语句拆分为两个语句?
Why does the result of a floating point operation depend on splitting one statement into two?
问:
我偶然发现了一个问题,浮点运算的结果取决于我是现在减去一个值 () 还是以后减去一个值 ()。为什么?f
f2
int main(int argc, char * argv[])
{
const float fResolution = 0.501f;
const int iDiff = -6; // some values lead to f == f2, like -1, -2, -3, -4 or -5
float f = iDiff * fResolution - 10.0f;
float f2 = iDiff * fResolution;
f2 -= 10.0f;
printf("Difference %f %f %f: %d\n", f, f2, f - f2, iDiff);
return 0;
}
输出:差值 -13.006000 -13.006001 0.000001:-6
我猜,它与浮点精度有关,但这里只有浮点数,那么和有什么区别呢?或者它可能是 Visual Studio 2010 中的特殊行为?f
f2
这当然是一个最小的例子。在现实世界中,我把计算提取成一个方法,有时减去-10。由于上述问题,提取方法后我的程序的输出有所不同。iDiff * fResolution
反汇编(调试模式):
const float fResolution = 0.501f;
00CC7872 fld dword ptr [__real@3f004189 (0D4AEACh)]
00CC7878 fstp dword ptr [ebp-0F8h]
const int iDiff = -6;
00CC787E mov dword ptr [ebp-104h],0FFFFFFFAh
float f = iDiff * fResolution - 10.0f;
00CC7888 fld dword ptr [ebp-0F8h]
00CC788E fmul qword ptr [__real@c018000000000000 (0D4AED8h)]
00CC7894 fsub qword ptr [__real@4024000000000000 (0D4AE58h)]
00CC789A fstp dword ptr [ebp-110h]
float f2 = iDiff * fResolution;
00CC78A0 fld dword ptr [ebp-0F8h]
00CC78A6 fmul qword ptr [__real@c018000000000000 (0D4AED8h)]
00CC78AC fstp dword ptr [ebp-11Ch]
f2 = f2 - 10.0f;
00CC78B2 fld dword ptr [ebp-11Ch]
00CC78B8 fsub qword ptr [__real@4024000000000000 (0D4AE58h)]
00CC78BE fstp dword ptr [ebp-11Ch]
答: 暂无答案
评论
sin(x) == sin(x)
false