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.
-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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With