Python2/3对同一个数学运算给出不同的答案…为什么?(计算百分比差异)

2024-07-08 10:00:39 发布

您现在位置:Python中文网/ 问答频道 /正文

python2和python3对于求两个量之间的百分比差的非常简单的数学操作,似乎得到了不同的答案。在

例如:

# Python 2.7.10
>>> def percent_difference(qty1, qty2):
...     diff = max(qty1, qty2) - min(qty1, qty2)
...     print(diff)
...     percent = diff / ( (qty1 + qty2) / 2)
...     print(percent)
... 
>>> percent_difference(1, 2)
1
1

# Python 3.6.2

>>> def percent_difference(qty1, qty2):
...     diff = max(qty1, qty2) - min(qty1, qty2)
...     print(diff)
...     percent = diff / ( (qty1 + qty2) / 2)
...     print(percent)
... 
>>> percent_difference(1, 2)
1
0.6666666666666666

这是怎么回事?在

(Python3是正确的)


Tags: 答案defdiff数学minmaxpython3百分比
3条回答

Python2Python3对整数的div操作处理不同。在

python3中,div操作将对整数和浮点进行相同的处理:

2/3 = 1.5
2.0/3 = 1.5
2/3.0 = 1.5
2.0/3.0 = 1.5

python2中,如果两个操作数都是整数,则它将截断浮点后面的数字:

^{pr2}$

您需要告诉Python您需要float输出。 尝试percent_difference(1.0, 2.0)

Python3更改了/运算符的行为。它过去依赖于所使用的类型(即integer / integer是整数除法,如果其中一个操作数是float,则得到float除法)。在

Python增强建议PEP-0238中解释了更改的基本原理:

The correct work-around is subtle: casting an argument to float() is wrong if it could be a complex number; adding 0.0 to an argument doesn't preserve the sign of the argument if it was minus zero. The only solution without either downside is multiplying an argument (typically the first) by 1.0. This leaves the value and sign unchanged for float and complex, and turns int and long into a float with the corresponding value.

相关问题 更多 >

    热门问题