# Thread: Wondering output???

1. ## Wondering output???

Code:
```#include <stdio.h>
int main( )
{
float a=1.0;
long i;
for(i=0; i<100; i++)
{
a = a - 0.01;
}
printf("a = %e\n",a);
}```
The output is: a = 6.591528745047981e-7 , not 0.0 as I expected!

But

Code:
```#include <stdio.h>
int main( )
{
float a=1.0;
long i;
for(i=0; i<100; i++)
{
a = a - 0.01;
}
/* now reverse */
for(i=0; i<100; i++)
{
a = a + 0.01;
}
/* check if exact reversal occurred */
if (a==1.0)
{
printf("correct! a=%e\n",a);
/* why is a==1.0? */
}
else
{
printf("error! a = %e\n",a);
}
}```
The output of this code is: correct! a = 1.0000000e + 000

I don't know why!
Please explain for me, thanks you very much!

2. Short answer: due to how floating point works.
Long answer: What Every Computer Scientist Should Know About Floating-Point Arithmetic

3. Originally Posted by Elysia
Short answer: due to how floating point works.
Long answer: What Every Computer Scientist Should Know About Floating-Point Arithmetic
Thanks Elysa. I'm have read but I don't understand clearly. I'm a newbie. Can you mention it in my example? Thanks you!

4. The article explains it well, I think. The problem is that cannot exactly represent numbers. Therefore, it will troublesome numbers "approximately". You see that the number is close to 0, but not exactly 0. That is because it cannot represent certain numbers exactly.
On the other hand, it can "undo" the damage by doing the reverse. That's because the number doesn't get truncated or anything like. It's just that the internal format cannot represent it exactly. The internal format is exact.

5. Short answer: you're not really subtracting 0.01 for a hundred times. You are really subtracting a number that's slightly less than that. 0.01 can not be represented exactly in floating point format so instead you are working with a close approximation. More like
0.009999993408... which is alright to 7 decimal places for the float data type.

While 0.01 looks like a nice number in base 10, it's a repeating decimal in base 2 - which is what the computer works with. The float data type allows 24 bits of precision after which the digits are cut off.

When you add back that inexact 0.01 for the same number of times you are backing out the damage, as Elysia said.

Think about what would happen if you repeatedly add 0.3333333 three times. That's one-third x three. You'd get 0.9999999. Not exactly 1.

Popular pages Recent additions