Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 340
Bob Stein Avatar asked Jan 23 '15 02:01

Bob Stein


People also ask

How do you check for negative infinity in Python?

The math. isinf() method checks whether a number is infinite or not. This method returns True if the specified number is a positive or negative infinity, otherwise it returns False.

How do you make positive infinity and negative infinity in Python?

1. Using float('inf') and float('-inf'): As infinity can be both positive and negative they can be represented as a float('inf') and float('-inf') respectively.

How do you check for Nan and infinity in Python?

Method 1: To check for infinite in python the function used is math. isinf() which only checks for infinite. To distinguish between positive and negative infinite we can add more logic that checks if the number is greater than 0 or less than 0. The code shows this in action.


1 Answers

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.

like image 106
jme Avatar answered Oct 02 '22 20:10

jme