Which one is more efficient using math.pow or the ** operator? When should I use one over the other?
So far I know that x**y
can return an int
Just for the protocol: The **
operator calls the built-in pow function which accepts an optional third argument (modulus) if the first two arguments are integer types.
So, if you intend to calculate remainders from powers, use the built-in function. The math.pow
may give you false results:
import math
base = 13
exp = 100
mod = 2
print math.pow(base, exp) % mod
print pow(base, exp, mod)
When I ran this, I got 0.0
in the first case which obviously cannot be true, because 13 is odd (and therefore all of it's integral powers). The math.pow
version uses limited accuracy which causes an error.
For sake of fairness, we must say, math.pow
can be much faster:
import timeit
print timeit.timeit("math.pow(2, 100)",setup='import math')
print timeit.timeit("pow(2, 100)")
Here is what I'm getting as output:
0.240936803195
1.4775809183
Some online examples
math.pow
)pow
on int values)pow
on float values)