A Floating Point Range Generator

vegaseat 3 Tallied Votes 731 Views Share

An example of a range generator that handles floating point numbers, appropriately called frange(). The function range() or the generator xrange() can only be used for integers. Note that xrange() now is range() in Python3.

# a range generator that handles floating point values
# tested with Python25 and Python31   by  vegaseat

def frange(start, stop=None, step=1.0, delta=0.0000001):
    """
    a range generator that handles floating point numbers
    uses delta fuzzy logic to avoid float rep errors
    eg. stop=6.4 --> 6.3999999999999986 would slip through
    """
    # if start is missing it defaults to zero
    if stop == None:
        stop = start
        start = 0.0
    # allow for decrement
    if step <= 0:
        while start > (stop + delta):
            yield start
            start += step
    else:
        while start < (stop - delta):
            yield start
            start += step

# test, should stop before 6.4
# without the fuzzy logic 6.4 would give a problem
for x in frange(6.0, 6.4, 0.1):
    print(x)

print("-"*20)

# test decrement
for x in frange(-6.0, -6.4, -0.1):
    print(x)

print("-"*20)

# test default start and step keyword arg
print(list(frange(5, step=0.5)))

"""my output -->
6.0
6.1
6.2
6.3
--------------------
-6.0
-6.1
-6.2
-6.3
--------------------
[0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5]
"""