为什么 round(2.49999999999999992) 返回 3 [英] Why does round(2.49999999999999992) returns 3

查看:41
本文介绍了为什么 round(2.49999999999999992) 返回 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写数学程序,但我对圆有一个很大的问题.所以在我的程序做了一些数学运算之后,它会将结果四舍五入.

一切正常,但如果 result == 2.499999999999999992 ,round 函数返回 3.0 而不是 2.0.

我该如何解决?

谢谢.

解决方案

正如@Pavel Anossov 在他的评论中所说 IEEE 754 中没有 2.49999999999999992 这样的东西,2.49999999999999992 == 2.5.浮点数可能始终对您的计算至关重要,因为在任何情况下(32/64/128 位浮点数),您都有一个精度限制.这显然也受限于 Python 浮点数.

有不同的选择来解决这个问题,你可以例如使用 decimal 库:

<预><代码>>>>从十进制导入 *>>>getcontext().prec = 6>>>十进制(1)/十进制(7)十进制('0.142857')>>>getcontext().prec = 28>>>十进制(1)/十进制(7)十进制('0.1428571428571428571428571429')

在这种情况下可以自己设置精度.decimal 在标准库中.

还有像 bigfloat 这样的第三方库,你可以使用(我没有这方面的经验)):

<预><代码>>>>从 bigfloat 导入 *>>>sqrt(2, precision(100)) # 以 100 位精度计算 sqrt(2)

但正如您所见,您始终必须选择精度.如果您真的不想失去任何精度,请使用 fractions(也在标准库中):

<预><代码>>>>从分数导入分数>>>a = 分数(16, -10)>>>一种分数(-8, 5)>>>一/23分数(-8, 115)>>>浮动(a/23)-0.06956521739130435

I'm working on the math program and I have a quite big problem with round. So after my program did some math, it rounds the result.

Everything works fine but if the result == 2.49999999999999992 , round function return 3.0 instead of 2.0.

How can I fix that?

Thanks.

解决方案

As @Pavel Anossov says in his comment there's no such thing as 2.49999999999999992 in IEEE 754, 2.49999999999999992 == 2.5.. Float might always be critical for your calculations, because in any case (32/64/128 bit float), you have a precision limit. This is obviously also limited for Python floats.

There are different options to deal with that, you could e.g. use the decimal library:

>>> from decimal import *
>>> getcontext().prec = 6
>>> Decimal(1) / Decimal(7)
Decimal('0.142857')
>>> getcontext().prec = 28
>>> Decimal(1) / Decimal(7)
Decimal('0.1428571428571428571428571429')

It's possible to set the precision yourself in that case. decimal is in the standard library.

There are also third party libraries like bigfloat, that you could use (I have no experience with it):

>>> from bigfloat import *
>>> sqrt(2, precision(100))  # compute sqrt(2) with 100 bits of precision

But as you can see, you always have to choose a precision. If you really don't want to lose any kind of precision, use fractions (also in the standard library):

>>> from fractions import Fraction
>>> a = Fraction(16, -10)
>>> a
Fraction(-8, 5)
>>> a / 23
Fraction(-8, 115)
>>> float(a/23)
-0.06956521739130435

这篇关于为什么 round(2.49999999999999992) 返回 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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