【发布时间】:2015-03-22 01:02:28
【问题描述】:
math.isinf() 测试合并在一起的正无穷或负无穷。什么是 pythonic 的方式来明确地测试它们?
测试正无穷大的方法:
x == float('+inf')math.isinf(x) and x > 0
测试负无穷大的方法:
x == float('-inf')math.isinf(x) and x < 0
拆卸方式一:
>>> 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
拆卸方式二:
>>> 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 似乎更喜欢方式 2,除了 x>0。
【问题讨论】: