I'm trying to solve a cross-platform issue that's cropping up and I'm not sure quite how to go about it. Here's a demonstration program:
#include <cmath>
#include <cstdio>
int main()
{
int xm = 0x3f18492a;
float x = *(float*)&xm;
x = (sqrt(x) + 1) / 2.0f;
printf("%f %x
", x, *(int*)&x);
}
The output on Windows when compiled in VS2010 is:
0.885638 3f62b92a
The output when compiled with GCC 4.8.1 (ideone.com sample) is:
0.885638 3f62b92b
These small mismatches end up ballooning into a serious problem over the course of a program that needs to run identically on multiple platforms. I'm not concerned so much about "accuracy" as that the results match each other. I tried switching the /fp
mode in VS to strict
from precise
, but that doesn't seem to fix it.
What other avenues should I look at to make this calculation have the same result on both platforms?
UPDATE: Interestingly, if I change the code like this, it matches across the platforms:
#include <cmath>
#include <cstdio>
int main()
{
int xm = 0x3f18492a;
float x = *(float*)&xm;
//x = (sqrt(x) + 1) / 2.0f;
float y = sqrt(x);
float z = y + 1;
float w = z / 2.0f;
printf("%f %x %f %x %f %x %f %x
", x, *(int*)&x, y, *(int*)&y, z, *(int*)&z, w, *(int*)&w);
}
I'm not sure it's realistic, however, to be walking through the code and changing all floating point operations like this!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…