# [Tutor] Re: floating point range() ?

Andrei project5 at redrival.net
Mon Jun 21 14:54:20 EDT 2004

```Dave S wrote on Thu, 17 Jun 2004 18:33:52 +0100:

> 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 ?

Write your own range function, say frange(). The implementation below is
simple and not as versatile as the built-in since it only allows positive
steps:

def frange(start, stop=0, step=1):
result = []
if step <= 0: # prevent endless loop
raise "step must be > 0"
start, stop = min(start, stop), max(start, stop)
i = start
while i < stop:
result.append(i)
i = i + step
return result

This function might surprise you though, due to the inaccuracies of
floating point:

>>> frange(1, 2, .2)
[1, 1.2, 1.3999999999999999, 1.5999999999999999, 1.7999999999999998,
1.9999999999999998]

Particularly the inclusion of 1.99999999 (in fact, 2) is the one you might
not have expected here.

--
Yours,

Andrei

=====
Real contact info (decode with rot13):
cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.

```