如何在Python中获得一个cube根

2024-04-30 00:53:29 发布

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

我最近看到一篇文章,关于在python中求平方根:How to calc square root in python?

我已经使用了sqrt(x)命令,但是我不知道如何使它适用于立方体根以及更高的根。

另外,我使用的是Python3.5.2。

有什么帮助吗?


Tags: toin命令文章calcrootsqrthow
1条回答
网友
1楼 · 发布于 2024-04-30 00:53:29

在Python中,可以通过以下方法找到浮动cube root

>>> def get_cube_root(num):
...     return num ** (1. / 3)
... 
>>> get_cube_root(27)
3.0

如果希望使用更通用的方法来查找nth root,可以使用以下基于Newton's method的代码:

# 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

相关问题 更多 >