Why is this separation incorrect?

I have a strange problem in Python: division does not work correctly:

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

Here are the results:

100
50
100
40
0

thank

+5
source share
3 answers

The above behavior is true for Python 2. The behavior has /been fixed in Python 3. In Python 2, you can use:

from __future__ import division

and then use /to get the desired result.

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

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

Or change one of the numbers to float.

>>> 5.0 / 2
2.5
+17
source

This is done correctly.

50/60 = 0

, 50.0/60.0 = 0.83333333333333337, , :

print  float(pointB[1]-pointA[1]) / (pointB[0]-pointA[0])
+9

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

float(pointB[1]-pointA[1]) / (pointB[0]-pointA[0])
+3
source

All Articles