gpt4 book ai didi

python - 与底商相比的整数除法 : why this surprising result?

转载 作者:太空狗 更新时间:2023-10-29 20:26:50 27 4
gpt4 key购买 nike

// Python 的“整数除法”运算符今天让我感到惊讶:

>>> math.floor(11/1.1)
10.0
>>> 11//1.1
9.0

documentation读作“x 和 y 的(取整)商”。那么,为什么 math.floor(11/1.1) 等于 10,而 11//1.1 等于 9?

最佳答案

因为1.1不能准确地用二进制形式表示;近似值略高于 1.1 - 因此除法结果有点太小了。

尝试以下操作:

在 Python 2 下,在控制台输入:

>>> 1.1
1.1000000000000001

在 Python 3.1 中,控制台将显示 1.1,但在内部,它仍然是相同的数字。

但是:

>>> 11/1.1
10.0

正如 gnibbler 指出的那样,这是在 float 的可用精度限制内“内部舍入”的结果。正如 MYYN 在他的评论中指出的那样,// 使用与 math.floor() 不同的算法来计算楼层划分结果,以便保留 a == (a//b)*b + a%b 以及可能的。

如果您需要这种精度,请使用Decimal 类型。

关于python - 与底商相比的整数除法 : why this surprising result?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2019588/

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