Python division

0 votes
I was trying to normalize a set of numbers from -100 to 0 to a range of 10-100 and was having problems only to notice that even with no variables at all, this does not evaluate the way I would expect it to:

>>> (20-10) / (100-10)
0
Float division doesn't work either:

>>> float((20-10) / (100-10))
0.0
If either side of the division is cast to a float it will work:

>>> (20-10) / float((100-10))
0.1111111111111111
Each side in the first example is evaluating as an int which means the final answer will be cast to an int. Since 0.111 is less than .5, it rounds to 0. It is not transparent in my opinion, but I guess that's the way it is.

What is the explanation?
Oct 13, 2018 in Python by ana1504.k
• 7,910 points
766 views

1 answer to this question.

0 votes
You're using Python 2.x, where integer divisions will truncate instead of becoming a floating point number.

>>> 1 / 2
0
You should make one of them a float:

>>> float(10 - 20) / (100 - 10)
-0.1111111111111111
or from __future__ import division, which the forces / to adopt Python 3.x's behavior that always returns a float.

>>> from __future__ import division
>>> (10 - 20) / (100 - 10)
-0.1111111111111111
answered Oct 13, 2018 by SDeb
• 13,300 points

Related Questions In Python

0 votes
1 answer

Number division in python

For Python 3, use the // operator: q = ...READ MORE

answered Apr 18, 2018 in Python by Nietzsche's daemon
• 4,260 points
624 views
0 votes
1 answer

What is Python division

You're using Python 2.x, where integer divisions ...READ MORE

answered Oct 17, 2018 in Python by Priyaj
• 58,020 points
438 views
0 votes
1 answer

Python error "ZeroDivisionError: division by zero"

Catch the error and handle it: try: ...READ MORE

answered May 31, 2019 in Python by Rhea
8,718 views
+1 vote
2 answers

Python error "ZeroDivisionError: float division by zero"

The error is thrown in this line matchPercentage ...READ MORE

answered May 21, 2020 in Python by Prabhakar
23,159 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,439 views
0 votes
1 answer
0 votes
1 answer

Python sort() function arguments

Both sort and sorted have three keyword arguments: cmp, key and reverse. L.sort(cmp=None, key=None, reverse=False) -- ...READ MORE

answered Oct 8, 2018 in Python by SDeb
• 13,300 points
8,039 views
0 votes
1 answer

How is Python 2.7.3 and Python 3.3 different?

raw_input() is not used in Python 3. Use input()  ...READ MORE

answered Sep 12, 2018 in Python by SDeb
• 13,300 points
926 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP