gpt4 book ai didi

Python 3.x 舍入行为

转载 作者:IT老高 更新时间:2023-10-28 12:25:32 25 4
gpt4 key购买 nike

我只是在重读 What’s New In Python 3.0它指出:

The round() function rounding strategy and return type have changed. Exact halfway cases are now rounded to the nearest even result instead of away from zero. (For example, round(2.5) now returns 2 rather than 3.)

round 的文档:

For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus n; if two multiples are equally close, rounding is done toward the even choice

所以,在 v2.7.3 下:

In [85]: round(2.5)
Out[85]: 3.0

In [86]: round(3.5)
Out[86]: 4.0

正如我所料。但是,现在在 v3.2.3 下:

In [32]: round(2.5)
Out[32]: 2

In [33]: round(3.5)
Out[33]: 4

这似乎违反直觉,与我的理解相反四舍五入(并且一定会绊倒人)。英语不是我的母语,但在我读到这篇文章之前,我以为我知道四舍五入是什么意思:-/我确定在引入 v3 时,一定有一些讨论这个,但我无法在搜索中找到一个很好的理由。

  1. 有没有人知道为什么会变成这样?
  2. 是否有任何其他主流编程语言(例如,C、C++、Java、Perl、 ..)进行这种(在我看来不一致)舍入?

我在这里错过了什么?

更新:@Li-aungYip 对“银行家的四舍五入”的评论给了我正确的搜索词/关键字来搜索,我发现了这个 SO 问题:Why does .NET use banker's rounding as default? ,所以我会仔细阅读。

最佳答案

Python 3 的方式(称为“round half to even”或“银行家的四舍五入”)目前被认为是标准的四舍五入方法,尽管一些语言实现还没有出现。

简单的“always round 0.5 up”技术会稍微偏向较大的数字。通过大量计算,这可能很重要。 Python 3.0 方法消除了这个问题。

常用的舍入方法不止一种。 IEEE 754, float 学的国际标准,定义 five different rounding methods (Python 3.0 使用的是默认的)。和there are others .

这种行为并不像应有的那样广为人知。如果我没记错的话,AppleScript 是这种舍入方法的早期采用者。 round command in AppleScript提供了几个选项,但在 IEEE 754 中,舍入到偶数是默认设置。显然,实现 round 命令的工程师已经厌倦了“让它像我一样工作”的所有请求在学校学到的”,他实现了这一点:round 2.5 rounding as described in school 是一个有效的 AppleScript 命令。 :-)

关于Python 3.x 舍入行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10825926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com