How to represent the infinite ?

Christophe Delord christophe.delord at free.fr
Thu Jun 20 13:21:46 EDT 2002


On Thu, 20 Jun 2002 17:02:33 +0200
"erreur" <dev at newdeal.ch> wrote:

You can try to redefine __cmp__ to handle all the cases.

For example :

Inf(+1) is +oo
Inf(-1) is -oo

class Inf:
	def __init__(self, sign=+1):
		self.sign = sign
	def __str__(self):
		return self.sign<0 and "-Inf" or "+Inf"
	def __cmp__(self, other):
		if isinstance(other, Inf):
			return cmp(self.sign, other.sign)
		else:
			return self.sign
	def __pos__(self): return Inf(self.sign)
	def __neg__(self): return Inf(-self.sign)

inf = Inf()
for t in ( \
	"+inf", "-inf",
	"10<-inf", "10>-inf", "10<+inf", "10>+inf",
	"-inf<10", "-inf>10", "+inf<10", "+inf>10",
	"-inf<-inf", "-inf==-inf", "-inf<+inf", "-inf==+inf",
	"-inf>=-inf", "-inf>=+inf"):
	print t, "=", eval(t)

This gives:

+inf = +Inf
-inf = -Inf
10<-inf = False
10>-inf = True
10<+inf = True
10>+inf = False
-inf<10 = True
-inf>10 = False
+inf<10 = False
+inf>10 = True
-inf<-inf = False
-inf==-inf = True
-inf<+inf = True
-inf==+inf = False
-inf>=-inf = True
-inf>=+inf = False

You may also redefine __add__, __mul__, ...


Best regards,
Christophe.

> 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
> 
> --------------------
> 
> 
> Not need to say to me that I can use 99999999999999 or -99999999999999 or I
> do not know what.
> Nor from a MAX_INT of the machine... bus Python can go higher.
> 
> Thank you for you answers (thank you to also answer by email if possible,
> because I will not have any more access to the news this weekend).
> 
> PS: Sorry for my English....
> 
> 


-- 

(o_   Christophe Delord                   _o)
//\   http://christophe.delord.free.fr/   /\\
V_/_  mailto:christophe.delord at free.fr   _\_V



More information about the Python-list mailing list