How to represent the infinite ?

Cliff Wells logiplexsoftware at earthlink.net
Thu Jun 20 14:23:28 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
> 
> --------------------

Here's a more complete infinite value (not that you'd need it, judging from
your requirements):

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

    def __str__(self):
        return "<%sinfinity>" % {-1: "-", 1: ""}[self.sign]

    def __repr__(self):
        return str(self)

    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

    def __mul__(self, n):
        retval = inf()
        retval.sign = self.sign * cmp(n, 0)
        return retval

    def __div__(self, n):
        return self * n

    def __add__(self, n):
        if isinstance(n, inf):
            if n.sign != self.sign:
                return 0
        return self

    def __sub__(self, n):
        return self + -n

    
if __name__ == '__main__':
    import sys
    
    m = -inf()
    n = inf()

    print m
    print n
    print m * n
    print n * n
    print m * m

    assert(m < n)
    assert(n > m)
    assert(m == m)
    assert(n == n)
    assert(m != n)
    assert(m < 0)
    assert(n > 0)
    assert(m != 0)
    assert(n
    assert(m < -sys.maxint)
    assert(n > sys.maxint)
    assert(m < -m)
    assert(n == -m)

    assert(n * 1 == n)
    assert(n * 1000 == n)
    assert(n * -1 == m)
    assert(n * -1000 == m)
    assert(n * 0 == 0)
    assert(m * 0 == 0)
    
    assert(n / 1 == n)
    assert(n / -1 == m)
    assert(n / -1000 == m)
    assert(m / 1 == m)
    assert(m / 1000 == m)
    assert(m / -1 == n)
    assert(m / -1000 == n)

    assert(m + 1 == m)
    assert(m - 1 == m)
    assert(n + 1 == n)
    assert(n - 1 == n)
    
    assert(n + m == 0)
    assert(n - m == n)
    assert(n - n == 0)
    assert(m + m == m)
    assert(m - m == 0)
    assert(m - n == m)
    
    # print 1 / m # exception: division by zero
    # print 1 / n # exception: division by zero



-- 
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