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>
range(0.5,5,0.5)
ValueError: range() step argument must not be zero
I used to use
numpy.arange
but had some complications controlling the number of elements it returns, due to floating point errors. So now I uselinspace
, e.g.:I helped add the function numeric_range to the package more-itertools.
more_itertools.numeric_range(start, stop, step)
acts like the built in function range but can handle floats, Decimal, and Fraction types.Eagerly evaluated (2.x
range
):Lazily evaluated (2.x
xrange
, 3.xrange
):Alternately:
A solution without numpy etc dependencies was provided by kichik but due to the floating point arithmetics, it often behaves unexpectedly. As noted by me and blubberdiblub, additional elements easily sneak into the result. For example
naive_frange(0.0, 1.0, 0.1)
would yield0.999...
as its last value and thus yield 11 values in total.A robust version is provided here:
Because the multiplication, the rounding errors do not accumulate. The use of
epsilon
takes care of possible rounding error of the multiplication, even though issues of course might rise in the very small and very large ends. Now, as expected:And with somewhat larger numbers:
The code is also available as a GitHub Gist.
Please note the first letter of Range is capital. This naming method is not encouraged for functions in Python. You can change Range to something like drange or frange if you want. The "Range" function behaves just as you want it to. You can check it's manual here [ http://reference.wolfram.com/language/ref/Range.html ].
Is there a range() equivalent for floats in Python? NO Use this: