Python数值计算的关注点

我在
python中计算了以下2个值,得到了不同的结果!如果有人能够解释为什么会这样发生,那就太好了.

(111-(111 2 * 17)* 3375)/( – 14)给出34947作为输出.

(111 – (111 2 * 17)* 3375)/(14)* – 1给出34948作为输出.

这两个术语在数学上是等价的.

最佳答案 这与舍入规则有关.考虑一个更简单的例子:

>>> -3/(-2)
1

>>> -3/2*-1
2

1.5向下舍入为1,-1.5向下舍入为-2.在某种程度上是一致的.

Doc reference:

Plain or long integer division yields an integer of the same type; the
result is that of mathematical division with the ‘floor’ function
applied to the result.

如果你想在Python 2.x中得到一个浮点结果,你需要一个显式转换(或者只是使用浮点文字),或者从__future__ import division开始.在Python 3.x中,除法总是产生一个浮点数(ref).

点赞