tags:

views:

135

answers:

6
+1  Q: 

Python division

Can somebody explain this to me? 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

EDIT: float division doesn't work either:

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

EDIT: right side typing ... who'd have thunk. This is what's happening:

>>> (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. Not transparent in my opinion but I guess that's the way it is.

+4  A: 

You need to change it to a float BEFORE you do the division. That is:

float(20 - 10) / (100 - 10)
A. Levy
This doesn't work, but you're on the right track. The right side has to be case to float first. This just take the int 0 and casts it to 0.0
Adam Nelson
@Adam Nelson: Works correctly for me. Check your parentheses.
Fred Larson
Actually, I'm wrong - but after looking at the docs, one should cast the right side first.
Adam Nelson
@Adam: It doesn't matter which side first.
KennyTM
A: 

Either way, it's integer division. 10/90 = 0. In the second case, you're merely casting 0 to a float.

Try casting one of the operands of "/" to be a float:

float(20-10) / (100-10)
Fred Larson
A: 

You're casting to float after the division has already happened in your second example. Try this:

float(20-10) / float(100-10)
David M
I've learned that python has conversions, not casts.
The MYYN
+2  A: 

You're putting Integers in so Python is giving you an integer back:

>>> 10 / 90
0

If if you cast this to a float afterwards the rounding will have already been done, in other words, 0 integer will always become 0 float.

If you use floats on either side of the division then Python will give you the answer you expect.

>>> 10 / 90.0
0.1111111111111111

So in your case:

>>> float(20-10) / (100-10)
0.1111111111111111
>>> (20-10) / float(100-10)
0.1111111111111111
Dave Webb
+7  A: 

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
KennyTM
+1: `from __future__ import division` -- very, very important.
S.Lott
A: 

Make at least one of them float, then it will be float division, not integer:

>>> (20.0-10) / (100-10)
0.1111111111111111

Casting the result to float is too late.

unbeli