如何使用Python找到立方根?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28014241/
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
How to find cube root using Python?
提问by Luke D
Here is how, this is the best way, I have found:
这是我发现的最佳方法:
x = int(raw_input("Enter an integer: "))
for ans in range(0, abs(x) + 1):
if ans ** 3 == abs(x):
break
if ans ** 3 != abs(x):
print x, 'is not a perfect cube!'
else:
if x < 0:
ans = -ans
print 'Cube root of ' + str(x) + ' is ' + str(ans)
Is there a better way, preferably one that avoids having to iterate over candidate values?
有没有更好的方法,最好是避免迭代候选值的方法?
回答by Bhargav Rao
The best way is to use simple math
最好的方法是使用简单的数学
>>> a = 8
>>> a**(1./3.)
2.0
EDIT
编辑
For Negative numbers
对于负数
>>> a = -8
>>> -(-a)**(1./3.)
-2.0
Complete Program for all the requirements as specified
完成指定的所有要求的程序
x = int(input("Enter an integer: "))
if x>0:
ans = x**(1./3.)
if ans ** 3 != abs(x):
print x, 'is not a perfect cube!'
else:
ans = -((-x)**(1./3.))
if ans ** 3 != -abs(x):
print x, 'is not a perfect cube!'
print 'Cube root of ' + str(x) + ' is ' + str(ans)
回答by NPE
You could use x ** (1. / 3)
to compute the (floating-point) cube root of x
.
您可以x ** (1. / 3)
用来计算 的(浮点)立方根x
。
The slight subtlety here is that this works differently for negative numbers in Python 2 and 3. The following code, however, handles that:
这里的微妙之处在于,对于 Python 2 和 3 中的负数,它的工作方式不同。 但是,以下代码处理了这个问题:
def is_perfect_cube(x):
x = abs(x)
return int(round(x ** (1. / 3))) ** 3 == x
print(is_perfect_cube(63))
print(is_perfect_cube(64))
print(is_perfect_cube(65))
print(is_perfect_cube(-63))
print(is_perfect_cube(-64))
print(is_perfect_cube(-65))
print(is_perfect_cube(2146689000)) # no other currently posted solution
# handles this correctly
This takes the cube root of x
, rounds it to the nearest integer, raises to the third power, and finally checks whether the result equals x
.
这取 的立方根x
,将其四舍五入到最接近的整数,进行三次幂,最后检查结果是否等于x
。
The reason to take the absolute value is to make the code work correctly for negative numbers across Python versions (Python 2 and 3 treat raising negative numbers to fractional powers differently).
取绝对值的原因是为了让代码在 Python 版本中正确处理负数(Python 2 和 3 将负数提升为分数幂的处理方式不同)。
回答by NPE
def cube(x):
if 0<=x: return x**(1./3.)
return -(-x)**(1./3.)
print (cube(8))
print (cube(-8))
Here is the full answer for both negative and positive numbers.
这是负数和正数的完整答案。
>>>
2.0
-2.0
>>>
Or here is a one-liner;
或者这里是单线;
root_cube = lambda x: x**(1./3.) if 0<=x else -(-x)**(1./3.)