Is there a way to step between 0 and 1 by 0.1?
I thought I could do it like the following, but it failed:
for i in range(0, 1, 0.1):
print i
Instead, it says that the step argument cannot be zero, which I did not expect.
Is there a way to step between 0 and 1 by 0.1?
I thought I could do it like the following, but it failed:
for i in range(0, 1, 0.1):
print i
Instead, it says that the step argument cannot be zero, which I did not expect.
Similar to R's
seq
function, this one returns a sequence in any order given the correct step value. The last value is equal to the stop value.Results
For completeness of boutique, a functional solution:
Best Solution: no rounding error
_________________________________________________________________________________
_________________________________________________________________________________
Or, for a set range instead of set data points (e.g. continuous function), use:
To implement a function: replace
x / pow(step, -1)
withf( x / pow(step, -1) )
, and definef
.For example:
in Python 2.7x gives you the result of:
but if you use:
gives you the desired:
Here is my solution which works fine with float_range(-1, 0, 0.01) and works without floating point representation errors. It is not very fast, but works fine:
more_itertools
is a third-party library that implements anumeric_range
tool:Output
This tool also works for
Decimal
andFraction
.