-1

I tried to sum some numbers in a for loop but it didn't go as I expected

float sum = 0;
int i;

printf("0.1+0.1=%f\n", 0.1 + 0.1);

for (i = 0; i<1000000; i++)
{
    sum = sum + 0.1;

}
printf("the sum need to be 100000 \n");
printf("the real sum is:\n %f\n", sum);


system("PAUSE");

this program prints:

0.1+0.1=0.200000

the sum need to be 100000

the real sum is:

100958.343750

Press any key to continue . . .

can you explain please this strange result?

Tal Sokolinsky
  • 88
  • 1
  • 14
  • 1
    Fear not: almost every developer falls into this trap once. You really need to learn about how [floating point numbers](https://en.wikipedia.org/wiki/Floating_point) work in computers. The important part is that floating point numbers cannot _exactly_ represent most numbers, you always have an error. In your case, the small errors add up until they become big. – DarkDust Apr 15 '16 at 09:12
  • thank you very much it has really helped me – Tal Sokolinsky Apr 15 '16 at 09:15

2 Answers2

0

the international standard for floating point numbers does not have an exact representation for some decimal numbers.

http://en.wikipedia.org/wiki/IEEE_754

It is due to the way they are stored in memory, the way the mantissa and exponent are stored.

https://en.wikipedia.org/wiki/Floating_point

This is also the reason why you should never compare two float numbers even if they look "the same".

I still remember how surprised I was the fist time a simple code comparing two float numbers didn't work :) This alone would open a dedicated universe of discussions. It is very worth reading anyway:

http://floating-point-gui.de/errors/comparison/

Maurizio Benedetti
  • 3,557
  • 19
  • 26
0

The floating numbers are stored in memory as x*2^y where x is between 0 and 1 with some precision and y is integer and so they accurately don't represent most numbers, they represent numbers "close enough".

When you do this addition multiple times, the error is just more visible. You can use double type for better accuracy.

Tomáš Šíma
  • 834
  • 7
  • 26