c - Same simple calculation, different results -
using gcc 4.8.2 (ubuntu 14.04) different results while calculating value same way. there's difference depending on architecture (32 bit / 64 bit) on systems tested.
#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  } what's reason , how can anticipate or avoid these differences ?
edit: casting fabs float doesn't change results, @ least on system (see comments oli charlesworth).
instead of forcing c compilers implement exacting standard floating-point computation java standards did, c99 standard allows variation respect ideal mode each operation done in order , rounded according ieee 754 format corresponding floating-point type.
you can ask gcc floating-point computation model following, , can use commandline options change behavior , make more predictable. there 2 cases:
- if going generate 387 code, compile recent gcc (4.8 should fine) , -std=c99. without (specifically, without-fexcess-precision=standardimplies), exact result of floating-point computation unpredictable, , allowing compiler produce different resultsresult1,result2,result3).-std=c99, values ofresult1,result3must identical. value ofresult2can different because intermediate assignmentresult2forces value @ point of computation roundedfloat.
- stop generating 387 code, generate sse2 code instead (options -msse2 -mfpmath=sse). in mode, 3 computations infabshas been replacedfabsfshould produce same result. has drawback of generating code compatible processors produced in last 12 years or so(!)
more information: post1, post2, written point of view of intends write static analyzer c programs precisely predicts results of floating-point computations.
Comments
Post a Comment