加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 如何获得立方根的整数?

发布时间:2020-12-20 11:33:18 所属栏目:Python 来源:网络整理
导读:我正在创建一个问题,需要我找到某些数字的立方根,其中一些有整数根,但其中很多都没有. 我有像125这样的数字,应该返回5的立方根,但Python返回4.99999 例: 125 ** (1.0/3.0)4.999999999999999 这是我的代码: processing = Truen = 12000while processing: if
我正在创建一个问题,需要我找到某些数字的立方根,其中一些有整数根,但其中很多都没有.

我有像125这样的数字,应该返回5的立方根,但Python返回4.99999
例:

>>> 125 ** (1.0/3.0)
4.999999999999999

这是我的代码:

processing = True
n = 12000
while processing:


    if (n ** (1.0/3.0)).is_integer() == True:
        print((n ** (1.0/3.0)),"is the cube root of ",n)
        processing = False
    else:
        n -= 1

解决方法

检查浮点相等性的标准方法是检查某个容差内的质量:

def floateq(a,b,tolerance=0.00000001):
    return abs(a-b) < tolerance

现在,您可以检查多维数据集根的舍入,转换为整数版本是否等于某个容差内的多维数据集根本身:

def has_integer_cube_root(n):
    floatroot = (n ** (1.0 / 3.0))
    introot = int(round(floatroot))
    return floateq(floatroot,introot)

用法:

>>> has_integer_cube_root(125)
True
>>> has_integer_cube_root(126)
False

但是,对于您的用例,这是非常不精确的:

>>> has_integer_cube_root(40000**3)
True
>>> has_integer_cube_root(40000**3 + 1)
True

您可以使用公差,但在某些时候,浮点数不足以获得所需的精度.

编辑:是的,正如评论所说,在这种情况下,您可以使用整数运算检查结果:

def has_integer_cube_root(n):
    floatroot = (n ** (1.0 / 3.0))
    introot = int(round(floatroot))
    return introot*introot*introot == n

>>> has_integer_cube_root(40000**3)
True
>>> has_integer_cube_root(40000**3 + 1)
False

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读