Click to See Complete Forum and Search --> : Power Function with no math libraries


smat42
February 11th, 2003, 12:46 AM
I need a power function that will work without including any math libraries. It has to support non-integer exponents. Anyone got any ideas?

galathaea
February 11th, 2003, 01:42 AM
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...

A_Stavros
February 12th, 2003, 10:47 AM
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...

Simon666
February 12th, 2003, 10:50 AM
Originally posted by A_Stavros
I hope I really understood...!

I'm afraid not:
Originally posted by smat42
It has to support non-integer exponents.

Galathaea's post is good and simple.