7

I've a strange issue in Python: the division is not performed correctly:

print pointB[1]
print pointA[1]
print pointB[0]
print pointA[0]
print  (pointB[1]-pointA[1]) / (pointB[0]-pointA[0])

These are the results:

100
50
100
40
0

thanks

Arya McCarthy
  • 8,554
  • 4
  • 34
  • 56
aneuryzm
  • 63,052
  • 100
  • 273
  • 488
  • 5
    its integer division in py 2.x, ie `5/6 = 0`, try to cast denom or numerator to float first – Anycorn Oct 03 '10 at 18:28
  • See http://stackoverflow.com/questions/117250/how-do-i-get-a-decimal-value-when-using-the-division-operator-in-python, http://stackoverflow.com/questions/1787249/why-doesnt-this-division-work-in-python, http://stackoverflow.com/questions/2958684/python-division – Pi Delport Oct 03 '10 at 18:43

3 Answers3

18

The above behavior is true for Python 2. The behavior of / was fixed in Python 3. In Python 2 you can use:

from __future__ import division

and then use / to get the result you desire.

>>> 5 / 2
2
>>> from __future__ import division
>>> 5 / 2
2.5

Since you are dividing two integers, you get the result as an integer.

Or, change one of the numbers to a float.

>>> 5.0 / 2
2.5
user225312
  • 126,773
  • 69
  • 172
  • 181
  • 7
    I'm not sure that it needs to be 'fixed' - the integer division works as it's supposed to do. Plus Python 3 has been out for almost 2 years... – Scott Griffiths Oct 03 '10 at 18:34
  • I will quote PEP238, `This makes expressions expecting float or complex results error-prone when integers are not expected but possible as inputs.` Also I doubt that he would be using Python 3.0 since I guess everyone makes it clear to stick to 2.6 for now. But I am also learning, so I maybe wrong. – user225312 Oct 03 '10 at 18:36
  • 2
    Many languages use integer division the Python 2 way (which isn't surprising if they lack dynamic typing). I guess that it was considered a design flaw though, or it wouldn't have been changed :) Btw the latest versions are 2.7 and 3.1 (with 3.2 already in alpha). – Scott Griffiths Oct 03 '10 at 18:45
  • small typo in first code example: `from __future__ import divis*i*on` – G-wizard Feb 29 '16 at 18:49
  • @ScottGriffiths it was considered a design flaw already over 15 years ago – Antti Haapala -- Слава Україні Apr 28 '16 at 12:44
9

It is done correctly.

50/60 = 0

Maybe you are looking for 50.0/60.0 = 0.83333333333333337, you can cast your variables to float to get that:

print  float(pointB[1]-pointA[1]) / (pointB[0]-pointA[0])
Ofri Raviv
  • 24,375
  • 3
  • 55
  • 55
3

This is how integer division works in python. Either use floats or convert to float in your calculation:

float(pointB[1]-pointA[1]) / (pointB[0]-pointA[0])
Ivo van der Wijk
  • 16,341
  • 4
  • 43
  • 57