-2

One operator seems to be produce wrong results in my C code. First of all, these are the lines of my code where I declare the variables (outside the main function, general scope):

FILE *fenergy;
float p1,p2,p3;
float FinalEnergy, EnergyState;

Then, I call a function that performs sequentially the next lines of code:

p1=FinalEnergy;
p2=EnergyState;
FinalEnergy=FinalEnergy+EnergyState;

fprintf(fenergy,"p1=%f p2=%f   Final=%f",p1,p2,FinalEnergy);

The file "fenergy" is correctly started by using the funcion:

fenergy=fopen(energy.txt,"w");

The values of all the variables seem to be correct in the first million of steps but then, the operation "+" in the line:

FinalEnergy=FinalEnergy+EnergyState; 

Gives a wrong output. This is a sample of the results output from the file written by the fprintf function:

p1=-130482984.000000 p2=-23.000000   Final=-130483008.000000 
p1=-130483008.000000 p2=-23.000000   Final=-130483032.000000  
p1=-130483032.000000 p2=-24.000000   Final=-130483056.000000 

I am getting crazy about this wrong result. There are only a sum operator and three variables, but my code gives that mistaken output. I have compiled and run my code in both windows 10 (MinGW) and linux (gcc).

I am really lost about this issue. Any suggestion would be highly appreciated.

Librex17
  • 21
  • 1
  • 2
    You realize you're only using 32-bit `float` variables, right? It looks like you're losing some precision as a result. Why don't you use 64-bit `double` variables instead? I personally never, ever use `float` in C. – Tom Karzes Jan 07 '18 at 20:55
  • Please post the [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) that shows the problem. Show the input, the expected output, and the actual output as text *in the question*. Aside: unless you cannot use `double` for a good reason, do not use the inferior `float`. – Weather Vane Jan 07 '18 at 20:58
  • `float` values have 24 bits of precision, which is around 7 decimal digits of precision. You're expecting 9 digits of precision. Use `double` values instead (53 bits = ~16 digits of precision). – ikegami Jan 07 '18 at 21:39

1 Answers1

1

this is a rounding error or a problem with accuracy / precision, cf. https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems ( https://en.wikipedia.org/wiki/Machine_epsilon, ... )

maybe try to use double instead of float

for arbitrary precision you can use special libraries like MPFR ( http://www.mpfr.org/ )

ralf htp
  • 9,149
  • 4
  • 22
  • 34