gpt4 book ai didi

python - 四舍五入时小数末尾5如何处理

转载 作者:太空宇宙 更新时间:2023-11-03 11:04:06 25 4
gpt4 key购买 nike

我正在使用 python 对 float 进行舍入,但我对计算机如何对数字进行舍入感到困惑。例如:

round(1.55, 1) = 1.6 # this is what I would expect; however
round(1.65, 1) = 1.6 #this is what confuses me. Is it supposed to be 1.7?

另一个例子:

round(1.85, 1) = 1.9
round(1.95, 1) = 1.9

我猜这可能与二进制和十进制之间的转换有关。我的问题是我怎么知道结尾的 5 是否会被省略?非常感谢您的帮助!

最佳答案

documentation描述了为什么会出现这种行为:

Note The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

相关,但超出了这个问题的范围,Floating Point Arithmetic limitations也是一本好书。

从那个页面开始,问题被扩展为:

The documentation for the built-in round() function says that it rounds to the nearest value, rounding ties away from zero. Since the decimal fraction 2.675 is exactly halfway between 2.67 and 2.68, you might expect the result here to be (a binary approximation to) 2.68. It’s not, because when the decimal string 2.675 is converted to a binary floating-point number, it’s again replaced with a binary approximation, whose exact value is

2.67499999999999982236431605997495353221893310546875

Since this approximation is slightly closer to 2.67 than to 2.68, it’s rounded down.

关于python - 四舍五入时小数末尾5如何处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24852052/

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