How to represent the infinite ?

Cliff Wells logiplexsoftware at earthlink.net
Thu Jun 20 13:47:15 EDT 2002


On Thu, 20 Jun 2002 17:02:33 +0200
erreur wrote:

> Will somebody have an idea, to represent the infinite one?
> 
> I have variables to initialize with is +inf (or - inf).  To be sure that
> later, all will be smaller (or larger) than my variables.
> I tried to redefine the operators on an object.  It goes for Inf>10 but I do
> not arrive for 10>Inf (because that takes > of Int).
> 
> --------------------
> 
> def __gt__(self, val):
> 
>     return 1
> 
> --------------------

Well, here's a start:

class inf(int):
    def __init__(self):
        int.__init__(self)
        self.sign = 1

    def __str__(self):
        return "<infinity>"

    def __repr__(self):
        return "<infinity>"

    def __cmp__(self, n):
        if isinstance(n, inf):
            return cmp(self.sign, n.sign)
        return self.sign
    
    def __neg__(self):
        retval = inf()
        retval.sign = self.sign * -1
        return retval

if __name__ == '__main__':
    import sys
    
    m = -inf()
    n = inf()
    assert(m < n)
    assert(n > m)
    assert(m == m)
    assert(n == n)
    assert(m != n)
    assert(m < 0)
    assert(n > 0)
    assert(m < -sys.maxint)
    assert(n > sys.maxint)
    assert(m < -m)
    assert(n == -m)
    



-- 
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726 x308  (800) 735-0555 x308





More information about the Python-list mailing list