range() for floats


Is there a range() equivalent for floats in Python?

>>> range(0.5,5,1.5)
[0, 1, 2, 3, 4]
>>> range(0.5,5,0.5)

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
ValueError: range() step argument must not be zero
9/1/2011 7:30:04 AM

Accepted Answer

I don't know a built-in function, but writing one like this shouldn't be too complicated.

def frange(x, y, jump):
  while x < y:
    yield x
    x += jump

As the comments mention, this could produce unpredictable results like:

>>> list(frange(0, 100, 0.1))[-1]

To get the expected result, you can use one of the other answers in this question, or as @Tadhg mentioned, you can use decimal.Decimal as the jump argument. Make sure to initialize it with a string rather than a float.

>>> import decimal
>>> list(frange(0, 100, decimal.Decimal('0.1')))[-1]

Or even:

import decimal

def drange(x, y, jump):
  while x < y:
    yield float(x)
    x += decimal.Decimal(jump)

And then:

>>> list(drange(0, 100, '0.1'))[-1]
5/23/2017 12:18:17 PM

You can either use:

[x / 10.0 for x in range(5, 50, 15)]

or use lambda / map:

map(lambda x: x/10.0, range(5, 50, 15))

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow