954,545 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

update of vegasets qrange

0
By Tony Veijalainen on Feb 10th, 2011 10:27 pm

Saw somebody was viewing this thread and thought the qrange needed one update. From post http://www.daniweb.com/code/snippet216627.html .

# qrange( [start,] stop[, step] ) is a generator, works similar to xrange()
def qrange(start, stop=None, step=1):
    """if start is missing it defaults to zero, somewhat tricky"""
    start, stop =  (0, start) if stop is None else  (start, stop)
    # allow for decrement
    while start > stop if step<0 else start < stop:
        yield start   # makes this a generator for new start value
        start += step

# test
print qrange(0, 10, 2)        # <generator object at 0x009D5E68>
print list(qrange(0, 10, 2))  # [0, 2, 4, 6, 8]
print list(qrange(10,0, -1))
print list(qrange(0,10,-1))

This has problem of accumulating error during repeated summing and ends up for example giving 51 values for qrange(5, step=0.1). Would need to stop near the end not only after the end (-delta or +delta)

There is ready alternative as long as you have numpy: numpy.arange.

import numpy
# qrange( [start,] stop[, step] ) is a generator, works similar to xrange()
delta = 1e-6
def qrange(start, stop=None, step=1):
    """if start is missing it defaults to zero, somewhat tricky"""
    start, stop =  (0, start) if stop is None else  (start, stop)
    # allow for decrement
    while start > stop + delta if step<0 else start < stop - delta:
        yield start   # makes this a generator for new start value
        start += step

# test
print qrange(0, 10, 2)        # <generator object at 0x009D5E68>
print list(qrange(0, 10, 2))  # [0, 2, 4, 6, 8]
vals = list(qrange(5, step = 0.1))
vals2 = list(numpy.arange(0,5,0.1))
print 'qrange', len(vals)
print vals
print 'arange', len(vals2)
print vals2
pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: