整数除法与地板商相比:为什么这个令人惊讶的结果? [英] Integer division compared to floored quotient: why this surprising result?

查看:56
本文介绍了整数除法与地板商相比:为什么这个令人惊讶的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

// Python 的整数除法"运算符让我惊讶,今天:

<预><代码>>>>math.floor(11/1.1)10.0>>>11//1.19.0

文档 读取x 和y".那么,为什么 math.floor(11/1.1) 等于 10,而 11//1.1 等于 9?

解决方案

因为 1.1 不能完全以二进制形式表示;近似值略高于 1.1 - 因此除法结果有点太小.

尝试以下操作:

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

<预><代码>>>>1.11.1000000000000001

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

但是:

<预><代码>>>>11/1.110.0

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

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

The // "integer division" operator of Python surprised me, today:

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

The documentation reads "(floored) quotient of x and y". So, why is math.floor(11/1.1) equal to 10, but 11//1.1 equal to 9?

解决方案

Because 1.1 can't be represented in binary form exactly; the approximation is a littler higher than 1.1 - therefore the division result is a bit too small.

Try the following:

Under Python 2, type at the console:

>>> 1.1
1.1000000000000001

In Python 3.1, the console will display 1.1, but internally, it's still the same number.

But:

>>> 11/1.1
10.0

As gnibbler points out, this is the result of "internal rounding" within the available precision limits of floats. And as The MYYN points out in his comment, // uses a different algorithm to calculate the floor division result than math.floor() in order to preserve a == (a//b)*b + a%b as well as possible.

Use the Decimal type if you need this precision.

这篇关于整数除法与地板商相比:为什么这个令人惊讶的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆