使用 gcc 4.8.2 (Ubuntu 14.04) 我得到不同的结果,而基本上以相同的方式计算一个值。根据我测试的系统上的体系结构(32 位/64 位),也存在差异。
#include <math.h>
#include <stdio.h>
int main()
{
float h = 0.11f;
float y = 0.11f;
float g = 1.37906f;
float x = 2.916949f;
float result1 = (h * y / fabs(g)) / x;
float result2 = h * y / fabs(g);
result2 /= x;
float result3 = (h * y / g) / x;
printf("%.20f \n", result1); //0.00300796888768672943
printf("%.20f \n", result2); //0.00300796912051737309
printf("%.20f \n", result3); //0.00300796912051737309 on x64
//0.00300796888768672943 on x32
}
这是什么原因,我该如何预测或避免这些差异?
编辑:铸造晶圆厂浮动不会改变结果,至少在我的系统上(参见 Oli Charlesworth 的评论)。