How do get more control over loop increments in Python?
One option:
def drange(start, stop, step):
while start < stop:
yield start
start += step
Usage:
for i in drange(0, 1, 0.01):
print i
you can use list comprehensions either:
print([i for i in [float(j) / 100 for j in range(0, 100, 1)]])
if you want control over printing i then do something like so:
print(['something {} something'.format(i) for i in [float(j) / 100 for j in range(0, 100, 1)]])
or
list(i for i in [float(j) / 100 for j in range(0, 100, 1)])
for i in [float(j) / 100 for j in range(0, 100, 1)]:
print i
Avoid compounding floating point errors with this approach. The number of steps is as expected, while the value is calculated for each step.
def drange2(start, stop, step):
numelements = int((stop-start)/float(step))
for i in range(numelements+1):
yield start + i*step
Usage:
for i in drange2(0, 1, 0.01):
print i