[Tutor] range() or xrange() for non-integers?
Denis Saussus
dsaussus at fugro-jason.com
Mon Sep 15 05:11:58 EDT 2003
This is right along the same line of thinking. I have this util function
which I find myself using nearly all the time:
def floatRange(a, b, inc):
"""
Returns a list containing an arithmetic progression of floats.
This is simply a float version of the built-in range(a, b, step)
function. The result is [ , ) as always in Python.
"""
try: x = [float(a)]
except: return False
for i in range(1, int(math.ceil((b - a ) / inc))):
x. append(a + i * inc)
return x
-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org]On
Behalf Of Andrei
Sent: Sunday, September 14, 2003 4:09 PM
To: tutor at python.org
Subject: [Tutor] Re: range() or xrange() for non-integers?
Terry Carroll wrote:
> On Sat, 13 Sep 2003, Bob Gailer wrote:
>
>
>>for x in xrange(-8.0, 8.0, 1.0):
>> print x/2
>
>
> Thanks.
>
> I'd thought of something along those lines, but that seems even worse for
> my particular application. I was going to need to vary the step to find
> the optimal one. (The actual application is to generate points to graph
> the x-component of electrical field generated by two particles.) So My
> first cut might be varying by .5, another by .1, etc. To have to vary by
> 1 and change the start and end points and an inner divisor to compensate
> seems very kludgy to me.
Why don't you just build your own rangef() function which returns a list?
>>> def rangef(min, max, step):
... result = []
... while 1:
... result.append(min)
... min = min+step
... if min>=max:
... break
... return result
...
>>> rangef(2,3,.2)
[2, 2.2000000000000002, 2.4000000000000004, 2.6000000000000005,
2.8000000000000007]
If desired, you can add some parameter checking routines so that min<max and
step>0 or whatever you need. You could also do (with a generator):
>>> def rangef(min=1, max=2, step=.2):
... while min<max:
... yield min
... min = min+step
...
>>> for item in rangef(3, 5, .3):
... print item
...
3
3.3
3.6
3.9
4.2
4.5
4.8
--
Yours,
Andrei
=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5 at bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur
yvfg, fb gurer'f ab arrq gb PP.
_______________________________________________
Tutor maillist - Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list