我最近看到这篇文章,关于在 python 中求平方根:How to calc square root in python?
我用过sqrt(x)
命令,但我不知道如何让它适用于立方根和更高的值。
此外,我使用的是 Python 3.5.2。
对此有什么帮助吗?
最佳答案
在 Python 中,您可能会通过以下方式找到 float 立方根
:
>>> def get_cube_root(num):
... return num ** (1. / 3)
...
>>> get_cube_root(27)
3.0
如果您想要更通用的方法来查找n次根
,您可以使用以下基于牛顿法
的代码:
# NOTE: You may use this function only for integer numbers
# k is num, n is the 'n' in nth root
def iroot(k, n):
u, s = n, n+1
while u < s:
s = u
t = (k-1) * s + n // pow(s, k-1)
u = t // k
return s
关于python - 如何在Python中获得立方根,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39155608/