-6

Python 2 and Python 3 seem to arrive at different answers for the very simple math operation of finding percentage difference between two quantities.

For example:

# 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

What's going on here?

(Python3 is correct)

right2clicky
  • 385
  • 4
  • 11

3 Answers3

1

Python 3 changed the behaviour of the / operator. It used to depend on the used types (i.e. integer / integer is integer division, if one of the operands is a float you get float division).

The rationale for the change is explained in the Python Enhancement Proposal 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.

filmor
  • 26,247
  • 3
  • 43
  • 46
0

You need to tell Python that you want float output. Try percent_difference(1.0, 2.0)

johnnyRose
  • 6,243
  • 16
  • 40
  • 58
Morasiu
  • 899
  • 10
  • 27
0

Python2 and Python3 treat the div operation for integers differently.

In python3 the div operation will treat integers and floats the same:

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

In python2 it will truncate the number after the floating points if both operands are integers:

2/3 = 1
2.0/3 = 1.5
2/3.0 = 1.5
2.0/3.0 = 1.5
AndreyF
  • 1,591
  • 1
  • 12
  • 23