I need a power function that will work without including any math libraries. It has to support non-integer exponents. Anyone got any ideas?
Printable View
I need a power function that will work without including any math libraries. It has to support non-integer exponents. Anyone got any ideas?
The simplest way would be to use the taylor expansions for the exponential function and natural logarithm:
e^x = 1 + x + x^2/2 + x^3/3! + ... (be sure to use proper numeric types!)
ln(1+x) = x - x^2/2 + x^2/3 - ... (-1<x<=1)
and then transform the power as:
a^b = e^(b*ln(a)).
You just must be sure to transform the logarithmic term to the bounds (most easily by dividing repeatedly by Euler's constant and at the same time adding one repeatedly to the result). There are some very interesting methods using recursions that might give better performance, but they would need a little more explanation...
I hope I really understood...!
The function is really simple:
int Power(int a, int p)
{
long result;
result=1;
for (int i=1; i<=p; i++)
{
result=result*a;
}
return result;
}
ready to use it.
You may need some overloadings for other data types.
I hope I helped...
I'm afraid not:Quote:
Originally posted by A_Stavros
I hope I really understood...!
Galathaea's post is good and simple.Quote:
Originally posted by smat42
It has to support non-integer exponents.