Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: 'inf is inf', but '-inf is not -inf'?

Python 3.7

While writing the search code for the maximum, I encountered a strange behavior of negative infinity. Can somebody explain why this behavior?

>>> inf = float('inf')
>>> inf is inf
True
>>> (-inf) is (-inf)
False

And I've already realized it's better to use == for comparison, but I'm interested in the answer to the question above.

like image 381
dakone22 Avatar asked Nov 29 '22 07:11

dakone22


2 Answers

-inf is an operation that produces a new float object, and you use it twice in the same expression. Two distinct objects are produced, because a Python implementation is not required to notice that both subexpressions could return a reference to the same object.

like image 34
chepner Avatar answered Dec 15 '22 11:12

chepner


inf is a variable, bound to a specific object. Any object is itself, so inf is inf.

-inf is an expression. It does math, and produces an object with value floating-point negative infinity. Python makes no promises about whether this will be the same object as any other object with that value. In your case, the two evaluations of -inf happened to produce different objects.

Again, there are no promises about what -inf is -inf will produce. The current CPython implementation happens to consistently produce False. PyPy's primitive handling produces True. A different Python version or implementation might inconsistently produce True or False based on current memory pressure, or whether you ran this as a script or interactively, or any other factor. CPython itself already has cases where object identity is different in a script or interactively; for example, this:

x = 1000
y = 1000
print(x is y)

prints different things in the current CPython implementation depending on whether you run it interactively.

like image 120
user2357112 supports Monica Avatar answered Dec 15 '22 12:12

user2357112 supports Monica