views:

118

answers:

3

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

+8  A: 

This will be fixed in Python 3.0, for the time being you can use:

from __future__ import divison

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
sukhbir
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
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.
sukhbir
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
+4  A: 

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
+8  A: 

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