How safe is a set of floats?

Thomas Nelson thn at mail.utexas.edu
Fri May 4 10:21:49 EDT 2007


I want to generate all the fractions between 1 and limit (with
limit>1) in an orderly fashion, without duplicates.

def all_ratios(limit):
    s = set()
    hi = 1.0
    lo = 1.0
    while True:
        if hi/lo not in s:
            s.add(hi/lo)
            yield (hi,lo)
        hi += 1
        if hi/lo > limit:
            lo += 1
            hi = lo

I use a set to keep from giving duplicates; but is this safe?  In C
they always tell you not to trust floating point equality comparisons,
since they may not work as you expect.  My code seems fine for the
limited amount I've tested, but I'm curious: is there a gaurantee
about sets of floats?  Or a warning?

Thanks,

Tom




More information about the Python-list mailing list