Also available at

Also available at my website and on Twitter @toshafanasiev

Monday, 6 September 2010

Python floating point range function

I recently noticed that Python's built in range( [start,] stop [,step] ) function does not support floating point values for the optional step parameter ( not 2.6.2 at least ), so until this is fixed, or in cases where you're stuck with it, here's a workaround:

def rangef( min, max, step=1.0 ):
 '''rangef( min, max, step=1.0 )\nlike range() but supports floats'''
 sf = 1.0 / step # scalefactor
 for i in range( int( min * sf ), int( max * sf ) ):
  yield i / sf

No comments:

Post a Comment