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 don't know a built-in function, but writing one like this shouldn't be too complicated.
As the comments mention, this could produce unpredictable results like:
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 thejump
argument. Make sure to initialize it with a string rather than a float.Or even:
And then:
There is no such built-in function, but you can use the following (Python 3 code) to do the job as safe as Python allows you to.
You can verify all of it by running a few assertions:
Code available on GitHub
using
itertools
: lazily evaluated floating point range:i wrote a function that returns a tuple of a range of double precision floating point numbers without any decimal places beyond the hundredths. it was simply a matter of parsing the range values like strings and splitting off the excess. I use it for displaying ranges to select from within a UI. I hope someone else finds it useful.
Pylab has
frange
(a wrapper, actually, formatplotlib.mlab.frange
):I think that there is a very simple answer that really emulates all the features of range but for both float and integer. In this solution, you just suppose that your approximation by default is 1e-7 (or the one you choose) and you can change it when you call the function.