While running the following lines of code:
int i,a;
for(i=0;i<=4;i++)
{
a=pow(10,i);
printf("%d\t",a);
}
I was surprised to see the output, it comes out to be 1
10
99
1000
9999
instead of 1
10
100
1000
10000
.
What could be the possible reason?
Note
If you think it's a floating point inaccuracy that in the above for loop when i = 2
, the values stored in variable a
is 99
.
But if you write instead
a=pow(10,2);
now the value of a comes out to be 100
. How is that possible?
No one spelt out how to actually do it correctly - instead of
pow
function, just have a variable that tracks the current power:This continuing multiplication by ten is guaranteed to give you the correct answer, and quite OK (and much better than pow, even if it were giving the correct results) for tasks like converting decimal strings into integers.
Mathematically, the integer power of an integer is an integer.
In a good quality
pow()
routine this specific calculation should NOT produce any round-off errors. I ran your code on Eclipse/Microsoft C and got the following output:This test does NOT indicate if Microsoft is using floats and rounding or if they are detecting the type of your numbers and choosing the appropriate method.
So, I ran the following code:
And got the following output:
The function
pow()
returns adouble
. You're assigning it to variablea
, of typeint
. Doing that doesn't "round off" the floating point value, it truncates it. Sopow()
is returning something like 99.99999... for 10^2, and then you're just throwing away the .9999... part. Better to saya = round(pow(10, i))
.This is to do with floating point inaccuracy. Although you are passing in
int
s they are being implicitly converted to a floating point type since thepow
function is only defined for floating point parameters.I can't even spell c, but I can tell you why.
You have set
a
to be anint
.pow()
generates a floating point number, that in SOME cases may be just a hair less than 100 or 10000 (as we see here.)Then you stuff that into the integer, which TRUNCATES to an integer. So you lose that fractional part. Oops. If you really needed an integer result, round may be a better way to do that operation.
Be careful even there, as for large enough powers, the error may actually be large enough to still cause a failure, giving you something you don't expect. Remember that floating point numbers only carry so much precision.