如何使用Python找到立方根? [英] How to find cube root using Python?

查看:1122
本文介绍了如何使用Python找到立方根?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我发现的最佳方法:

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?

推荐答案

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

You could use x ** (1. / 3) to compute the (floating-point) cube root of x.

这里的微妙之处在于,这对于 Python 2 和 3 中的负数的工作方式不同.但是,以下代码处理了这个问题:

The slight subtlety here is that this works differently for negative numbers in Python 2 and 3. The following code, however, handles that:

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.

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.

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

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找到立方根?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆