# <float>range(0.0,100.0,0.1)

Thu May 18 03:50:23 EDT 2000

``` on 2000-05-17 15:57, Warren Postma (embed at geocities.com) wrote:
: how do you do this:
:
: for i in range(0.0, 100.0, 0.1):
: print i

import UserList

class frange(UserList.UserList):
"""
frange(stop) # assume start=0, step=1
frange(start, stop) # assume step=1
frange(start, stop, step)
returns a list of values from start up to stop, with step step.
Unlike range(), stop value is included in the list, if it is equal
to the last value of the arithmetic sequence.
If the returned list is too big, you may want to use xfrange class.
This class is not resistant to rounding errors, e.g. on my computer:

>>> frange(0.7, 0, -0.1)
[0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1]
>>> frange(0.7, -0.05, -0.1)
[0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, -1.11022302463e-16]

"""

def __init__(self, *args):
l = len(args)
if l == 1: # only to
f = 0
t = args[0]
self.step = 1
elif l == 2: # from, to
self.start, self.stop = args
self.step = 1
elif l == 3:
self.start, self.stop, self.step = args
self.data = []
k = (self.stop-self.start)/self.step+1
self.data = map(lambda x, f=self.start, s=self.step: f+s*x, range(max(0, int(k))))

def __repr__(self):
return "frange(%i, %i, %i)" % (self.start, self.stop, self.step)

def __str__(self):
return str(self.data)

def __len__(self):
return len(self.data)

class xfrange:
"""
xfrange(stop) # assume start=0, step=1
xfrange(start, stop) # assume step=1
xfrange(start, stop, step)
Similar to frange, but constructs values on the fly, making it suitable
for large sequences.
Constructs values from start up to stop, with step step.
Unlike xrange(), stop value is included in the list, if it is equal
to the last value of the arithmetic sequence.
This class is not resistant to rounding errors.
"""

def __init__(self, *args):
l = len(args)
if l == 1: # only to
f = 0
t = args[0]
step = 1
elif l == 2: # from, to
f, t = args
step = 1
elif l == 3:
f, t, step = args
self.length = max(0, int((t-f)/step+1)) # number of items
self.start = f
self.stop = t
self.step = step

def __getitem__(self, i):
r = self.start+self.step*i
if (self.step>0 and r<=self.stop) or (self.step<0 and r>=self.stop):
return r
raise IndexError, "index out of range"

def __len__(self):
return self.length

def __str__(self):
return str(frange(self.start, self.stop, self.step))

def __repr__(self):
return "xfrange(%i, %i, %i)" % (self.start, self.stop, self.step)

--
-----------------------------------------------------------