简体   繁体   中英

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.

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.

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

I want to add one point: in Python, when we use id() function, is operator, == operator, etc, the real target we're working with is value , not variable .

a is b equals to id(a) == id(b) .

In your code, inf = float('inf') will produce a value named inf .

inf is also an expression, which will be evaluated to a value.

inf is inf will be True , because the evaluated values of two expressions are same one, in fact.

In Python, focusing on values is better and easier.

For example, in CPython implementation:

a = 1
b = 1
a is b # will be true

a = 10000
b = 10000
a is b # will be false

a = '10000'
b = '10000'
a is b # will be true

If we focus on variable, such thing is weird. If we focus on values, and if I tell you that CPython implementation has cache pool, which is used for small int and some literal str value, such thing is simple again:

Because of cache pool, small int 1 is cached, str '10000' is cached too, but big int 10000 is not cached so it will be created two times.

Try to focus on values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM