[Tutor] floating point range() ?
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Thu Jun 17 16:23:26 EDT 2004
On Thu, 17 Jun 2004, Dave S wrote:
> Is there a floating point range() type builtin ?
>
> I need to generate a sequence for a 'for loop' every 0.5
>
> for i in reange(0,1000,5)
> j=float(i)/10
> print j
>
> The above works but seems clumbsy.
>
> Is there a better way ?
Hi Dave,
I don't think there is a built-in equivalent for range() with floats.
However, it isn't too bad to write something ourselves:
###
def frange(start, stop, skip=1.0):
"""A range-like generator that returns numbers in the interval
[start, stop).
"""
i = start
while i < stop:
yield i
i += skip
###
Here's an example of how to use frange():
###
>>> for x in frange(0, 10, 0.5):
... print x
...
0
0.5
1.0
1.5
2.0
2.5
3.0
3.5
4.0
4.5
5.0
5.5
6.0
6.5
7.0
7.5
8.0
8.5
9.0
9.5
###
Does this seem reasonable?
Hope this helps!
More information about the Tutor
mailing list