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.
My versions use the original range function to create multiplicative indices for the shift. This allows same syntax to the original range function. I have made two versions, one using float, and one using Decimal, because I found that in some cases I wanted to avoid the roundoff drift introduced by the floating point arithmetic.
It is consistent with empty set results as in range/xrange.
Passing only a single numeric value to either function will return the standard range output to the integer ceiling value of the input parameter (so if you gave it 5.5, it would return range(6).)
Edit: the code below is now available as package on pypi: Franges
Suprised no-one has yet mentioned the recommended solution in the Python 3 docs:
Once defined, the recipe is easy to use and does not require
numpy
or any other external libraries, but functions likenumpy.linspace()
. Note that rather than astep
argument, the thirdnum
argument specifies the number of desired values, for example:I quote a modified version of the full Python 3 recipe from Andrew Barnert below:
I am only a beginner, but I had the same problem, when simulating some calculations. Here is how I attempted to work this out, which seems to be working with decimal steps.
I am also quite lazy and so I found it hard to write my own range function.
Basically what I did is changed my
xrange(0.0, 1.0, 0.01)
toxrange(0, 100, 1)
and used the division by100.0
inside the loop. I was also concerned, if there will be rounding mistakes. So I decided to test, whether there are any. Now I heard, that if for example0.01
from a calculation isn't exactly the float0.01
comparing them should return False (if I am wrong, please let me know).So I decided to test if my solution will work for my range by running a short test:
And it printed True for each.
Now, if I'm getting it totally wrong, please let me know.
This is my solution to get ranges with float steps.
Using this function it's not necessary to import numpy, nor install it.
I'm pretty sure that it could be improved and optimized. Feel free to do it and post it here.
The output is:
Here's a solution using itertools:
Usage Example:
You can use this function: