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

我正在创建一个问题,需要我找到某些数字的立方根,其中一些有整数根,但其中很多都没有.

我有像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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值