Monday, February 23, 2009

Fastest raise to power

If you need raising to power some non standard object, like matrices or something overloaded with a integer exponent you can use this algorith:

a any type that know operator*, b int






if b is even
(a*a)^(b/2)=


if b is odd

using a recursive function your calculation will be faster (overall with big exponents) than the usual way.

A little example code:
double mpow (double, int);
double mpow2(double, int);

double mpow(double b, int exp)
{
if (exp < 0)
{
b = 1/b;
exp *= -1;
}

return mpow2(b,exp);
}

double mpow2(double b, int exp)
{
if (exp > 2)
{
if (exp%2)
return b*mpow(b*b,(int)exp/2);
else
return mpow(b*b,exp/2);
}
else if (2 == exp)
return b*b;
else if (1 == exp)
return b;

return 1.0; // exp == 0
}

This example is about floats, so it is nothing more than the usual pow(), yet if you need raising to power try to avoid a*a*a*a*...*a as that is really slow.

Author : Ezzetabi

0 nhận xét:

Post a Comment