Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this division not performed correctly?

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

like image 706
aneuryzm Avatar asked Oct 03 '10 18:10

aneuryzm


People also ask

Why is my division not working in Python?

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.

How do you divide correctly in Java?

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 .

Does division always result in a float?

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.

How do you divide in Python?

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.


2 Answers

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
like image 173
user225312 Avatar answered Sep 21 '22 21:09

user225312


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])
like image 22
Ofri Raviv Avatar answered Sep 20 '22 21:09

Ofri Raviv