I was trying to write a program to calculate the value of x^n using a while
loop:
#include <stdio.h>
#include <math.h>
int main()
{
float x = 3, power = 1, copyx;
int n = 22, copyn;
copyx = x;
copyn = n;
while (n)
{
if ((n % 2) == 1)
{
power = power * x;
}
n = n / 2;
x *= x;
}
printf("%g^%d = %f\n", copyx, copyn, power);
printf("%g^%d = %f\n", copyx, copyn, pow(copyx, copyn));
return 0;
}
Up until the value of 15 for n
, the answer from my created function and the pow
function (from math.h
) gives the same value; but, when the value of n
exceeds 15, then it starts giving different answers.
I cannot understand why there is a difference in the answer. Is it that I have written the function in the wrong way or it is something else?
You are mixing up two different types of floating-point data. The pow
function uses the double
type but your loop uses the float
type (which has less precision).
You can make the results coincide by either using the double
type for your x
, power
and copyx
variables, or by calling the powf
function (which uses the float
type) instead of pow
.
The latter adjustment (using powf
) gives the following output (clang-cl compiler, Windows 10, 64-bit):
3^22 = 31381059584.000000
3^22 = 31381059584.000000
And, changing the first line of your main
to double x = 3, power = 1, copyx;
gives the following:
3^22 = 31381059609.000000
3^22 = 31381059609.000000
Note that, with larger and larger values of n
, you are increasingly likely to get divergence between the results of your loop and the value calculated using the pow
or powf
library functions. On my platform, the double
version gives the same results, right up to the point where the value overflows the range and becomes Infinity
. However, the float
version starts to diverge around n = 55
:
3^55 = 174449198498104595772866560.000000
3^55 = 174449216944848669482418176.000000