Power Function

Hi Everyone,

I have a question about a function I was trying to write. It is supposed to raise a number to a positive integer. I also used it to demonstrate overloading a function.

One problem is that for 3.5642^5 my power() function gives 575.188720703125, while pow() from cmath.h gives 575.18867866693928. Can anyone explain what is happening?

Another is that large exponents (ie, 2^40) give 0. Is there a variable/function type large than double that I can use?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

int power(int a, int b)
{
     int c=a;
     for (int n=b; n>1; n--) c*=a;
     return c;
}

double power(double a, int b)
{
      float c=a;
      for (int n=b; n>1; n--) c*=a;
      return c;
}

int main()
{
    cout<<power(2,25)<<endl;
    cout<<setprecision(20)<<power(3.5642,5)<<endl;
    cout<<pow(3.5642,5)<<endl;
    system("pause");
    return 0;
}


Thanks for any suggestions.
It most likely has to do with floating point arithmetic. Because of the way the computer stores floating point numbers, it can't be exactly accurate. cmath.h pow() probably uses a different, more efficient technique than yours, which leads to a slightly different numerical result.

Additionally, your power function accepts two doubles and returns a double, but you declare c as a float - why?
Thanks for the information.

Also, that was a mistake that I did not see.

Edit: I changed c from float to double. Now both power(3.5642,5) and pow(3.5642,5) are identical to the amount of digits I can display. Thanks for spotting that.
Last edited on
Topic archived. No new replies allowed.