Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

Testing for positive infinity, or negative infinity, individually in Python

math.isinf() tests for positive or negative infinity lumped together. What's the pythonic way to test for them distinctly?

Ways to test for positive infinity:

  1. x == float('+inf')
  2. math.isinf(x) and x > 0

Ways to test for negative infinity:

  1. x == float('-inf')
  2. math.isinf(x) and x < 0

Disassembly Way 1:

>>> def ispinf1(x): return x == float("inf")
...
>>> dis.dis(ispinf1)
  1           0 LOAD_FAST                0 (x)
              3 LOAD_GLOBAL              0 (float)
              6 LOAD_CONST               1 ('inf')
              9 CALL_FUNCTION            1
             12 COMPARE_OP               2 (==)
             15 RETURN_VALUE

Disassembly Way 2:

>>> def ispinf2(x): return isinf(x) and x > 0
...
>>> dis.dis(ispinfs)
  1           0 LOAD_GLOBAL              0 (isinf)
              3 LOAD_FAST                0 (x)
              6 CALL_FUNCTION            1
              9 JUMP_IF_FALSE_OR_POP    21
             12 LOAD_FAST                0 (x)
             15 LOAD_CONST               1 (0)
             18 COMPARE_OP               4 (>)
        >>   21 RETURN_VALUE

This answer seems to favor Way 2 except for the x>0.

question from:https://stackoverflow.com/questions/28102302/testing-for-positive-infinity-or-negative-infinity-individually-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The "pythonic" way is to go with what's readable and maintainable.

That said, x == float("inf") and x == float("-inf") are slightly more readable to me, and I'd prefer them. math.isinf(x) and x > 0 is faster, but only on the order of about 40 nanoseconds per call.

So unless you're checking a whole lot of numbers, it isn't going to make much of a difference in running time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...