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 it's not.
Thanks.
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 it's not.
Thanks.
Why don't you increase the magnitude of i for the loop and then reduce it when you need it.
for i * 100 in range(0, 100, 10):
print i / 100.0
The range() built-in function returns a sequence of integer values, I'm afraid, so you can't use it to do a decimal step.
I'd say just use a while loop:
i = 0.0
while i <= 1.0:
print i
i += 0.1
If you're curious, Python is converting your 0.1 to 0, which is why it's telling you the argument can't be zero.
Python's range() can only do integers, not floating point. In your specific case, you can use a list comprehension instead:
[x * 0.1 for x in range(0, 10)]
(Replace the call to range with that expression.)
For the more general case, you may want to write a custom function or generator.
And if you do this often, you might want to save the generated list r
r=map(lambda x: x/10.0,range(0,10))
for i in r:
print i
Building on 'xrange([start], stop[, step])', you can define a generator that accepts and produces any type you choose (stick to types supporting +
and <
):
>>> def drange(start, stop, step):
... r = start
... while r < stop:
... yield r
... r += step
...
>>> i0=drange(0.0, 1.0, 0.1)
>>> ["%g" % x for x in i0]
['0', '0.1', '0.2', '0.3', '0.4', '0.5', '0.6', '0.7', '0.8', '0.9', '1']
>>>
You can also use the numpy library (which isn't part of standard library but is relatively easy to obtain) which has the arange function:
>>> import numpy as np >>> np.arange(0,1,0.1) array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
as well as the linspace function which lets you have control over what happens at the endpoint (non-trivial for floating point numbers when things won't always divide into the correct number of "slices"):
>>> np.linspace(0,1,11) array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ]) >>> np.linspace(0,1,10,endpoint=False) array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
The Python Cookbook has a recipe for this: http://code.activestate.com/recipes/66472/
Be sure to check the comments; they include improved versions and discussion of errors (for example, gimel's solution may accumulate errors due to repeated addition of floating point numbers).