How do I do exponentiation in python?
86,488
Solution 1
^
is the xor operator.
**
is exponentiation.
2**3 = 8
Solution 2
You can also use the math
library. For example:
import math
x = math.pow(2,3) # x = 2 to the power of 3
Solution 3
if you want to repeat it multiple times - you should consider using numpy:
import numpy as np
def cube(number):
# can be also called with a list
return np.power(number, 3)
print(cube(2))
print(cube([2, 8]))
Author by
Admin
Updated on October 27, 2020Comments
-
Admin over 3 years
def cube(number): return number^3 print cube(2)
I would expect
cube(2) = 8
, but instead I'm gettingcube(2) = 1
What am I doing wrong?
-
Teepeemm almost 9 years
-
Jeru Luke almost 6 yearsthe essence of being numpythonic
-
Krishnadas PC almost 3 yearsCan you explain how it works when there are fractions like
2 ** 4.5
? -
ShadowRanger over 2 years@Teepeemm: Mind you,
math.pow
is basically 100% useless;**
does the job without an import, and doesn't force conversion tofloat
. And the built-inpow
is the only one accepting three arguments to efficiently perform modular exponentiation. I can't think of a single time I've ever wanted to perform exponentiation that implicitly converted my integer inputs to floating point (the only timemath.pow
is even remotely useful, andfloat(x) ** y
would achieve that anyway).