user6510891
user6510891

Reputation:

Find range between floats in python

I am trying to find if a number falls in a range, and one or both of the numbers of the range can be floats.

I.E.

if x in range(0.5, 3.5):
    pass

I understand range only accepts integers

So, how do I find a range between one or both floats in python. I searched around and found frange() and numpy.linspace(). Yet the former it seems is for incrementing with a float and linspace just creates a list of numbers between a range equally. All of the solutions either want floor division by 10 or have to do with incrementing.

I looked here range() for floats already and not my question.

Thanks.

Upvotes: 0

Views: 809

Answers (4)

Markyroson
Markyroson

Reputation: 109

As suggested above, the Math module would be one way of going about this, however, it is not necessary and could be done in a one (or two) liner

Either as

if 0.5 < x < 3.5:
    pass

or in one line, such as

if 0.5 < x < 3.5: pass

Upvotes: 0

Aasmund Eldhuset
Aasmund Eldhuset

Reputation: 37950

if 0.5 <= x < 3.5:
    pass

You might want to change the inequality signs depending on whether you want the ends to be inclusive or exclusive.

A "range" in Python is not an abstract mathematical notion of "all the numbers between these two numbers", but either an actual list of numbers (range() in Python 2) or a generator which is capable of producing a sequence of numbers (xrange() in Python 2 or range() in Python 3). Since there are infinitely many real numbers between two given numbers, it's impossible to generate such a list/sequence on a computer. Even if you restrict yourselves to floating-point numbers, there might be millions or billions of numbers in your range.

For the same reason, even though your code would have worked for integers (but only in Python 2), it would have been terribly inefficient if your endpoints were far apart: it would first generate a list of all integers in the range (consuming both time and memory), and then traverse the list to see if x is contained in it.

If you ever try to do a similar thing in other languages: most languages don't allow double comparisons like this, and would instead require you to do something like if 0.5 < x and x < 3.5.

Upvotes: 2

jpp
jpp

Reputation: 164623

You can use math module to perform the rounding, if you want to keep the same syntax. This assumes x is an integer.

from math import ceil, floor

if x in range(floor(0.5), ceil(3.5)):
    pass

Upvotes: 1

sam
sam

Reputation: 376

if 0.5 < x < 3.5:
    pass

I don't think you need a function at all here.

Upvotes: 2

Related Questions