python - 如何在Python中获得立方根

标签 python

我最近看到这篇文章,关于在 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/

相关文章:

python - 在 Python 中使用数量时消除单位

python - dataframe:删除具有某些类型值的对象类型列

python - 如何使用Python Pandas使用动态字符串来过滤数据帧

python - 如何将嵌套列表的字符串转换回嵌套列表?

python - 如何匹配ip地址

python - 使用 Seaborn 绘制 CDF + 累积直方图

python - 如何连接 Pandas 中的年份和月份列?

python - 如何理解/使用 Python difflib 输出?

python - 当第二个数组 > 0 时创建新数组

javascript - 生成 JSON 的 md5 哈希并在 Python 和 JavaScript 中进行比较