3

How can I make an for loop in python with steps of 0.01?

I tried this but it doesn't work:

 for X0 in range (-0.02, 0.02, 0.01):
     for Y0 in range (-0.06, 0.09, 0.01): 

it says TypeError: range() integer end argument expected, got float.

Steven
  • 323
  • 1
  • 6
  • 17
  • See this question if you want to code a `range` function that accepts floats or if you want to use numpy: http://stackoverflow.com/questions/477486/python-decimal-range-step-value – Nicolas Apr 25 '13 at 16:44
  • 2
    This question has been asked and answered before. http://stackoverflow.com/questions/477486/python-decimal-range-step-value – AlexLordThorsen Apr 25 '13 at 16:46

3 Answers3

8
[x * 0.01 for x in xrange(10)]

will produce

[0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09]
mjallday
  • 9,796
  • 9
  • 51
  • 71
5

The python range only takes integers as the error message indicates. If you want to use float steps, you can either use numpy's arange or just divide a integer range:

>>> import numpy as np
>>> print np.arange(-0.02, 0.02, 0.01)
array([-0.02, -0.01,  0.  ,  0.01])

in your example:

for X0 in np.arange(-0.02, 0.02, 0.01):
    for Y0 in np.arange(-0.06, 0.09, 0.01):   

or:

>>> print [a/0.01 - 0.02 for a in range(4)]
[-0.02, -0.01, 0.0, 0.009999999999999998]
tiago
  • 22,602
  • 12
  • 72
  • 88
5

If you don't want to use a library:

def float_range(a,b,c):
    while a < b:
        yield a
        a += c
for X0 in float_range (-0.02, 0.02, 0.01):
    for Y0 in float_range (-0.06, 0.09, 0.01): 
        print X0, Y0
Hal Canary
  • 2,154
  • 17
  • 17