为什么在Python中舍入浮点数时会发生这种情况? [英] Why does this happen when rounding floating numbers in Python?

查看:112
本文介绍了为什么在Python中舍入浮点数时会发生这种情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究在Python中舍入浮点数,并且以下行为似乎很奇怪:

I am looking into rounding floating point numbers in Python and the following behavior seems quite strange:

代码:

a = 203.25
print '%.2f'%(a/10.)
print '%.2f'%(round(a/10., 2))
print '%.2f'%(0.1*a)

输出:

20.32
20.32
20.33

为什么第一种情况尤其是第二种情况失败?

Why does the first and especially the second case fail?

推荐答案

http://en.wikipedia.org/wiki /Rounding#Round_half_to_even

圆整到一半
偏见较少的平局决胜规则是一半到一半,即:

Round half to even
A tie-breaking rule that is less biased is round half to even, namely:

如果y的分数为0.5,则q是最接近y的偶数整数. 因此,例如+23.5变为+ 24,+ 24.5变为+24;而−23.5 变为-24,而变为-24.5.

If the fraction of y is 0.5, then q is the even integer nearest to y. Thus, for example, +23.5 becomes +24, as does +24.5; while −23.5 becomes −24, as does −24.5.

此方法对称地对待正值和负值,并且 因此没有符号偏差.更重要的是,为了合理 y值的分布,即四舍五入后的期望值(平均值) 数字与原始数字相同.但是这个 规则将为偶数引入接近零的偏见,并且 奇数偏向无穷大.

This method treats positive and negative values symmetrically, and is therefore free of sign bias. More importantly, for reasonable distributions of y values, the expected (average) value of the rounded numbers is the same as that of the original numbers. However, this rule will introduce a towards-zero bias for even numbers, and a towards-infinity bias for odd ones.

最近舍入法的这种变体也称为 unbiased 四舍五入,收敛四舍五入,统计学家四舍五入,荷兰语 四舍五入,高斯四舍五入,奇偶四舍五入银行家的 四舍五入,并广泛用于簿记.

This variant of the round-to-nearest method is also called unbiased rounding, convergent rounding, statistician's rounding, Dutch rounding, Gaussian rounding, odd-even rounding or bankers' rounding, and is widely used in bookkeeping.

这是IEEE 754计算功能中使用的默认舍入模式 和运算符.

This is the default rounding mode used in IEEE 754 computing functions and operators.

>>> "%.2f"%20.325
'20.32'
>>> "%.2f"%20.335
'20.34'
>>> "%.2f"%20.345
'20.34'
>>> "%.2f"%20.355
'20.36'

所以真正的问题应该是为什么第三种情况失败了?

So the real question should be why does the third case fail?

203.25可以精确地用浮点表示法表示,但是0.1不能,它比0.1

203.25 can be expressed exactly in the floating point representation, however 0.1 cannot, it turns out to be a tiny bit more than 0.1

>>> 0.1*203.25
20.325000000000003

因此它会四舍五入

这篇关于为什么在Python中舍入浮点数时会发生这种情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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