Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Power function giving different answer than math.pow function in C

Tags:

c

pow

math.h

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?

like image 816
Abir Mondal Avatar asked May 01 '26 20:05

Abir Mondal


2 Answers

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
like image 98
Adrian Mole Avatar answered May 04 '26 13:05

Adrian Mole


When I run your code I get this:

3^22 = 31381059584.000000
3^22 = 31381059609.000000

This would be because pow returns a double but your code uses float. When I changed to powf I got identical results:

3^22 = 31381059584.000000
3^22 = 31381059584.000000

So simply use double everywhere if you need high resolution results.

like image 43
Lundin Avatar answered May 04 '26 11:05

Lundin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!