如何使用Python查找cube根?

2024-04-19 23:11:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我发现,这是最好的方法:

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)

有没有更好的方法,最好是避免迭代候选值的方法?


Tags: 方法inanforinputrawifis
3条回答

最好的方法是用简单的数学

>>> a = 8
>>> a**(1./3.)
2.0

编辑

对于负数

>>> a = -8
>>> -(-a)**(1./3.)
-2.0

按规定完成所有要求的程序

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)
def cube(x):
    if 0<=x: return x**(1./3.)
    return -(-x)**(1./3.)
print (cube(8))
print (cube(-8))

这是负数和正数的完整答案。

>>> 
2.0
-2.0
>>> 

或者这是一条单行线

root_cube = lambda x: x**(1./3.) if 0<=x else -(-x)**(1./3.)

可以使用x ** (1. / 3)计算x的(浮点)立方根。

这里稍微微妙的一点是,对于Python2和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

这取x的立方根,将其舍入到最接近的整数,提升到第三次方幂,最后检查结果是否等于x

采用绝对值的原因是为了使代码在Python版本中正确地处理负数(Python 2和3对将负数提升为小数幂的处理方式不同)。

相关问题 更多 >