1

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?

2 Answers 2

3

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.)

Sign up to request clarification or add additional context in comments.

4 Comments

Nice contribution with the __future__ module.
Yeah, apparently I have to use n/(variable+0.00). That works, but it's not looking good.
@RomaValcer: edited my answer. use float() on either of the variables rather than adding 0.00 to force one to be a float.
yeah, looks much better. Anyways, sometimes python dynamic typization (if I chose right word) can cause trouble.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.