为什么 Python 中的 round() 函数将半浮点数舍入为最接近的偶数?

Barbara Streisand
发布: 2024-10-17 15:48:03
原创
622 人浏览过

Why Does round() Function Round Half Float Numbers to the Nearest Even Number in Python?

Understanding Half Float Number Rounding Behavior in Python

When dealing with half float numbers in Python, the round() function can exhibit an unexpected behavior, as illustrated by the following code snippet:

<code class="python">for i in range(1, 15, 2):
    n = i / 2
    print(n, "=&gt;", round(n))</code>
登录后复制

This code prints:

0.5 =&gt; 0
1.5 =&gt; 2
2.5 =&gt; 2
3.5 =&gt; 4
4.5 =&gt; 4
5.5 =&gt; 6
6.5 =&gt; 6
登录后复制

Instead of rounding up all floating values, round() rounds them to the nearest even number. This peculiar behavior is attributed to "rounding half to even," also known as "bankers rounding."

Cause of Bankers Rounding

According to the Python documentation, round() rounds half towards even to prevent compounding rounding errors. By rounding to the nearest even number, the overall rounding effect is averaged out.

Correcting the Rounding Behavior

To obtain the desired rounding behavior, specifically rounding up from half, the decimal module can be utilized. By defining a local context and setting the rounding parameter to ROUND_HALF_UP, Python's rounding function can be customized.

Here's an example demonstrating how to round up from half using the decimal module:

<code class="python">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, '=&gt;', n.to_integral_value())</code>
登录后复制

The output of this code is:

0.5 =&gt; 1
1.5 =&gt; 2
2.5 =&gt; 3
3.5 =&gt; 4
4.5 =&gt; 5
5.5 =&gt; 6
6.5 =&gt; 7
登录后复制

Conclusion

To achieve correct rounding behavior for half float numbers, the decimal module in Python provides the necessary tools for specifying the desired rounding strategy. By utilizing the ROUND_HALF_UP option, half float numbers can be rounded up consistently, as shown in the provided example.

以上是为什么 Python 中的 round() 函数将半浮点数舍入为最接近的偶数?的详细内容。更多信息请关注PHP中文网其他相关文章!

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