0

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.

4 Answers4

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

Aasmund Eldhuset
  • 37,289
  • 4
  • 68
  • 81
2
if 0.5 < x < 3.5:
    pass

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

sam
  • 366
  • 1
  • 11
1

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
jpp
  • 159,742
  • 34
  • 281
  • 339
  • Thanks, people pointed out to change to use equality operators. This got me thinking "theoretically" if I wanted to use how would it work. I will go with different syntax but this answer is good, thanks. :) –  Mar 08 '18 at 19:12
  • For the number to be *in between* you must swap `floor` and `ceil`. Logically, it should fail for both `x = 0` and `x = 4`. – Jongware Mar 08 '18 at 19:20
  • I think question is ambiguous, you can easily subtract or add 1 to these numbers if required. – jpp Mar 08 '18 at 19:28
0

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
Markyroson
  • 109
  • 10