update of vegasets qrange

TrustyTony 0 Tallied Votes 587 Views Share

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))
TrustyTony 888 pyMod Team Colleague Featured Poster

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
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.