Python round函数中的一个错误

huangapple go评论75阅读模式
英文:

A bug in the Python round function

问题

有关Python的round函数执行四舍五入操作时存在问题。为什么不同的数字会有不同的四舍五入结果?
我对这个函数感到困惑。

英文:

There is an issue with the Python round function when performing rounding operations. Why do different numbers have different rounding results?
I feel confused about this function

enter image description here

I don't know why....

答案1

得分: 1

在Python中,round总是会将数字四舍五入到最接近的偶数,如果它在两个数字之间等距离。

对于支持round()的内置类型,值会四舍五入到最接近的10的幂次方减去ndigits的倍数;如果有两个倍数距离一样近,那么会向偶数方向进行四舍五入(因此,例如round(0.5)和round(-0.5)都是0,round(1.5)是2)。任何整数值都是有效的ndigits(正数、零或负数)。如果省略了ndigits或为None,则返回值是整数。否则,返回值与number具有相同的类型。

更多信息请参阅:https://docs.python.org/3/library/functions.html#round

英文:

In Python, round will always round to the closest even number if it is equally spaced between two numbers.

>For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2). Any integer value is valid for ndigits (positive, zero, or negative). The return value is an integer if ndigits is omitted or None. Otherwise, the return value has the same type as number.

https://docs.python.org/3/library/functions.html#round

huangapple
  • 本文由 发表于 2023年7月18日 16:03:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76710662.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定