Pregunta

I have this simple code:

[n/2 for n in range(100, 200)]

But, strangely enough, it returns [50,50,51,51,52,52,etc], so it uses integer division instead of normal one (I need it to output [50,50.5,51,51.5,etc]) Why is it happening?

¿Fue útil?

Solución

In Python 2, dividing 2 integers will always produce an integer. (In Python 3, you get "real" division)

You can rewrite your code as:

[n/2.0 for n in range(100, 200)]

or in the case where you have 2 variables:

[float(n)/othervar for n in range(100, 200)]

to get the expected behavior,

or add

from __future__ import division

at the start of the file to get the Python 3 behavior now.

To answer the "why" part of the question, this is a holdover from C's division semantics (although Python made the choice to always floor the result instead of rounding toward 0, so you don't even get the true C integer division semantics.)

Otros consejos

Try [n/2.0 for n in range(100, 200)] to make it a float operation. By passing 2 as an integer and all numbers in the range as an integer Python is treating the result as an integer. You need Floating Point Arithmetic. See here for more details.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top