I've read that cmath
calculates pow(a,b)
by performing exp(b*log(a))
. This should not be used when b
is an integer, since it slows down calculations a lot. What alternatives are there when
- calculating a lot of successive
pow()
s with the same constanta
- it is known beforehand that
b
will definitely be an integer?
I am looking for fast alternatives which are efficient in these particular scenarios.
There are a number of faster alternatives I've collected over the years that typically rely on a
recursive
implementation of the function, and bit shifts to handle multiplication when warranted. The following provide functions tailored tointeger
,float
anddouble
. They come with the normaldisclaimer:
while faster not all possible test have been run and the user should validate input is sane before calling and on return... blah, blah, blah.. But, they are pretty darn useful:I believe proper attribution goes to Geeks for Geeks Pow(x,n) as pointed out by blue moon. I had long since lost the links.. That looks like them. (minus a tweak or two).