为什么浮点数舍入的结果令人惊讶?

Linda Hamilton
发布: 2024-10-17 15:49:03
原创
830 人浏览过

Why Does Float Rounding Surprise with Even Results?

Half Float Rounding-Up Dilemma

Encountering an oddity with the round() function? Observe the following behavior:

for i in range(1, 15, 2):
    n = i / 2
    print(n, "=>", round(n))
登录后复制

You might expect the floating values to consistently round up, yet they surprisingly round to the nearest even number.

Reason Behind the Behavior

The documentation for Numeric Types clarifies this peculiar behavior with the statement "round(x[, n]) x rounded to n digits, rounding half to even." This is known as bankers rounding. Instead of persistent rounding up or down, which would amplify rounding errors, bankers rounding compensates by targeting the closest even number.

Solution for Controlled Rounding

To handle rounding precisely, leverage the decimal module. This module equips you with options to specify specific rounding strategies. For instance, to round up from half:

>>> from decimal import localcontext, Decimal, ROUND_HALF_UP
>>> with localcontext() as ctx:
...     ctx.rounding = ROUND_HALF_UP
...     for i in range(1, 15, 2):
...         n = Decimal(i) / 2
...         print(n, '=>', n.to_integral_value())
...
0.5 => 1
1.5 => 2
2.5 => 3
3.5 => 4
4.5 => 5
5.5 => 6
6.5 => 7
登录后复制

以上是为什么浮点数舍入的结果令人惊讶?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!