我如何在python中求幂?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30148740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:01:18 来源:igfitidea点击:
How do I do exponentiation in python?
提问by Rohan Sobha
def cube(number):
return number^3
print cube(2)
I would would expect cube(2) = 8
, but instead I'm getting cube(2) = 1
我会期望cube(2) = 8
,但相反我得到cube(2) = 1
What am I doing wrong?
我究竟做错了什么?
回答by Iron Fist
You can also use the math
library. For example:
您也可以使用math
图书馆。例如:
import math
x = math.pow(2,3) # x = 2 to the power of 3
回答by omerbp
if you want to repeat it multiple times - you should consider using numpy:
如果你想多次重复 - 你应该考虑使用 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]))