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?
#include <iostream>
#include <iomanip>
#include <cmath>
usingnamespace 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;
}
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?
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.