Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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?

1 Answer

0 votes
by (106k points)

You are getting that exception because you are using Python 2.x, where integer divisions will truncate instead of becoming a floating-point number.

>>> 1 / 2 

0

To get the correct output you should make one of them a float:

>>> float(10 - 20) / (100 - 10)

 -0.1111111111111111

Or you can use the from __future__ import division, which the forces / to adopt Python 3.x's behaviour that always returns a float.

>>> from __future__ import division 

>>> (10 - 20) / (100 - 10) 

-0.1111111111111111

To know more about this you can have a look at the following video tutorial:-

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...