floatrange
is a Python module which mimics Python's builtin range()
function with support of float values (Python range() builtin only works with int values). As for range()
, the given stop value is not in the generated sequence.
Its primary usage is in for
loops on arithmetic progression of non-integer values. For operations like contains test (Python in
operator), computation of value index
, and count
of value occurences in a floatrange, a precision parameter allows to limit problems with floating point computation.
It works as is with Python 2 and Python 3.
Example from source documentation:
>>> from floatrange import floatrange
>>> floatrange(5)
floatrange(0.0, 5.0, 1.0)
>>> list(floatrange(5))
[0.0, 1.0, 2.0, 3.0, 4.0]
>>> list(floatrange(3.2,5.4,0.2))
[3.2, 3.4000000000000004, 3.6, 3.8000000000000003, 4.0, 4.2, 4.4, 4.6000000000000005, 4.800000000000001, 5.0, 5.2]
>>> list(floatrange(-6,-8,-0.3))
[-6.0, -6.3, -6.6, -6.9, -7.2, -7.5, -7.8]
>>> 6 in floatrange(1,8)
True
>>> 6.1 in floatrange(1,8,1,prec=0.2)
True
>>> 6.1 in floatrange(1,8,1,prec=0.05)
False
>>> list(reversed(floatrange(5)))
[4.0, 3.0, 2.0, 1.0, 0.0]
>>> list(floatrange(10.1,9.7,-0.1))
[10.1, 10.0, 9.9, 9.799999999999999]
If you have the scipy's numpy package installed, see numpy.arange()
and numpy.linspace()
. If you have heavy computation, this is the way to go.
Note these differences between numpy functions and floatrange:
prec
to deal with inaccurate floating point computation.And searching for Python float range, or frange will give you other solutions (see also comments on these solutions when available).