actually disregard that last little bit of text, 'frange(10,.5) '. I meant to say 'frange(10,step = -.5)', because without 'step = -.5', it would turn up an infinite loop. At line 5, please add:
if start and not end:
print 'frange error: got start argument but not end'
exit()
Also, if you are trying to go up from zero to a number by a float, please declare what is the start/end/step argument. IE use 'frange(0,10,.5)' not 'frange(10,.5)'
fallopiano
Junior Poster in Training
68 posts since Jun 2009
Reputation Points: 10
Solved Threads: 6
even more minimalistic while still keeping the fastest speed would be:
def frange(s,e=None,S=None):
if e==None:e=s;s=0.0
if S==None:S=1.0
L=[];n=s
if e>s:
while n<e:L.append(n);n+=S
elif e<s:
while n>e:L.append(n);n-=S
return L
fallopiano
Junior Poster in Training
68 posts since Jun 2009
Reputation Points: 10
Solved Threads: 6
There is a nasty bug in all your approaches to frange() ...
# both frange functions written by Luke Endres (fallopiano)
# If your going to use it, please give credit!
def frange(start, end=None, step=None):
'A range function that can accept float increments'
if end == None:
end = start
start = 0.0
if step == None:
step = 1.0
L = []
n = float(start)
if end > start:
while n < end:
L.append(n)
n += step
return L
elif end < start:
while n > end:
L.append(n)
n -= step
return L
# testing ...
# would expect numbers 6.0 to 6.3, but 6.4 slips through!
for k in frange(6.0, 6.4, 0.1):
print(k)
"""my result -->
6.0
6.1
6.2
6.3
6.4 oops!!!
"""
vegaseat
DaniWeb's Hypocrite
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
I have another frange function. I remember writing it after reading a discussion about frange functions in the activestate code snippets
def frange (start ,stop ,n ):
"""frange(start, stop, n) -> list of n float
A range function which returns n equally spaced floating numbers
from start to stop"""
L =[0.0 ]*n
nm1 =n -1
nm1inv =1.0 /nm1
start ,stop =start *nm1inv ,stop *nm1inv
for i in range (n ):
L [i ]=(start *(nm1 -i )+stop *i )
return L
It was included in the P1function class in this other snippet http://www.daniweb.com/code/snippet217163.html . The idea of passing the number of points instead of a step is to avoid the problem mentioned above.
Note that range could be replaced by xrange if python < 3.
Gribouillis
Posting Maven
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691