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:

  1. if going generate 387 code, compile recent gcc (4.8 should fine) , -std=c99. without (specifically, without -fexcess-precision=standard implies), exact result of floating-point computation unpredictable, , allowing compiler produce different results result1, result2 , result3). -std=c99, values of result1 , result3 must identical. value of result2 can different because intermediate assignment result2 forces value @ point of computation rounded float.
  2. stop generating 387 code, generate sse2 code instead (options -msse2 -mfpmath=sse). in mode, 3 computations in fabs has been replaced fabsf should 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

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -