取整** 0.5和math.sqrt [英] Rounding ** 0.5 and math.sqrt

查看:337
本文介绍了取整** 0.5和math.sqrt的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,是

n**0.5  # or
math.sqrt(n) 

识别数字是一个完美的平方?具体来说,我应该担心使用

recognized when a number is a perfect square? Specifically, should I worry that when I use

int(n**0.5)  # instead of
int(n**0.5 + 0.000000001)

由于精度误差,我可能会意外地得出比实际平方根小1的数字吗?

I might accidentally end up with the number one less than the actual square root due to precision error?

推荐答案

是的,您应该担心:

In [11]: int((100000000000000000000000000000000000**2) ** 0.5)
Out[11]: 99999999999999996863366107917975552L

In [12]: int(math.sqrt(100000000000000000000000000000000000**2))
Out[12]: 99999999999999996863366107917975552L

显然添加0.000000001在这里也无济于事...

obviously adding the 0.000000001 doesn't help here either...

@DSM指出,您可以使用十进制库:

As @DSM points out, you can use the decimal library:

In [21]: from decimal import Decimal

In [22]: x = Decimal('100000000000000000000000000000000000')

In [23]: (x ** 2).sqrt() == x
Out[23]: True

对于超过10**999999999的数字,只要您检查精度(可配置),它将抛出错误而不是错误的答案...

for numbers over 10**999999999, provided you keep a check on the precision (configurable), it'll throw an error rather than an incorrect answer...

这篇关于取整** 0.5和math.sqrt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆