在 Python 中单独测试正无穷大或负无穷大
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28102302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Testing for positive infinity, or negative infinity, individually in Python
提问by Bob Stein
math.isinf()tests for positive or negative infinity lumped together. What's the pythonic way to test for them distinctly?
math.isinf()测试集中在一起的正无穷大或负无穷大。明确测试它们的pythonic方法是什么?
Ways to test for positive infinity:
测试正无穷大的方法:
x == float('+inf')
math.isinf(x) and x > 0
x == float('+inf')
math.isinf(x) and x > 0
Ways to test for negative infinity:
测试负无穷大的方法:
x == float('-inf')
math.isinf(x) and x < 0
x == float('-inf')
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 answerseems to favor Way 2 except for the x>0.
除了 x>0 之外,这个答案似乎有利于方式 2。
采纳答案by jme
The "pythonic" way is to go with what's readable and maintainable.
“pythonic”方式是采用可读和可维护的方式。
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 nanosecondsper call.
这就是说,x == float("inf")
和x == float("-inf")
稍微更具可读性给我,我宁愿他们。math.isinf(x) and x > 0
速度更快,但每次调用仅大约 40纳秒。
So unless you're checking a whole lot of numbers, it isn't going to make much of a difference in running time.
因此,除非您检查大量数字,否则不会对运行时间产生太大影响。
回答by muon
there is also numpy
还有 numpy
>>> import numpy as np
>>> np.isneginf([np.inf, 0, -np.inf])
array([False, False, True], dtype=bool)
>>> np.isposinf([np.inf, 0, -np.inf])
array([ True, False, False], dtype=bool)
and then there is general isinf
然后是一般 isinf
>>> np.isinf([np.inf, 0, -np.inf])
array([ True, False, True], dtype=bool)