snippetpythonCriticalCanonical
How do I use a decimal step value for range()?
Viewed 0 times
howuseforstepdecimalvaluerange
Problem
How do I iterate between 0 and 1 by a step of 0.1?
This says that the step argument cannot be zero:
This says that the step argument cannot be zero:
for i in range(0, 1, 0.1):
print(i)Solution
Rather than using a decimal step directly, it's much safer to express this in terms of how many points you want. Otherwise, floating-point rounding error is likely to give you a wrong result.
Use the
If you really want to use a floating-point step value, use
Floating-point rounding error will cause problems, though. Here's a simple case where rounding error causes
Use the
linspace function from the NumPy library (which isn't part of the standard library but is relatively easy to obtain). linspace takes a number of points to return, and also lets you specify whether or not to include the right endpoint:>>> 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])If you really want to use a floating-point step value, use
numpy.arange:>>> import numpy as np
>>> np.arange(0.0, 1.0, 0.1)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])Floating-point rounding error will cause problems, though. Here's a simple case where rounding error causes
arange to produce a length-4 array when it should only produce 3 numbers:>>> numpy.arange(1, 1.3, 0.1)
array([1. , 1.1, 1.2, 1.3])Code Snippets
>>> 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])>>> import numpy as np
>>> np.arange(0.0, 1.0, 0.1)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])>>> numpy.arange(1, 1.3, 0.1)
array([1. , 1.1, 1.2, 1.3])Context
Stack Overflow Q#477486, score: 1237
Revisions (0)
No revisions yet.