[Tutor] range()-like function for dealing with floats...?

Kent Johnson kent37 at tds.net
Fri Mar 30 13:41:52 CEST 2007


Joydeep Mitra wrote:
> Hi all,
> I need to generate a sequence of real numbers that are evenly spaced. I 
> have used loops for this purpose until now, but it gets kinna messy when 
> you gotta do it a number of times in a program.
> The range function, as per my knowledge, accepts parameters and return 
> values only as integers.
> Is there a function in python, which performs the task of the range() 
> function with floats?

There is nothing built-in but it is easy to make your own using a generator:
In [1]: def frange(start, stop, step):
    ...:     i = start
    ...:     while i < stop:
    ...:         yield i
    ...:         i += step
    ...:

In [2]: for i in frange(1, 3, .5):
    ...:     print i
    ...:

1
1.5
2.0
2.5

More on generators here:
http://www.python.org/doc/2.2.3/whatsnew/node5.html

Kent


More information about the Tutor mailing list