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
An input from the user is a string by default. In order to perform mathematical operations on an input, you need to either change it to an integer or a float using int() or float() respectively.
When dividing two integers, Java uses integer division. In integer division, the result is truncated (fractional part thrown away) and not rounded to the closest integer. For example: 99 / 10 == 9 .
Adding subtracting or multiplying two ints always yields an int result, but division is different. The result of division is always a float value, even if the division comes out even.
Types of division operators in Python In Python, there are two types of division operators: / : Divides the number on its left by the number on its right and returns a floating point value. // : Divides the number on its left by the number on its right, rounds down the answer, and returns a whole number.
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
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With