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

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


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.


there is also 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

>>> np.isinf([np.inf, 0, -np.inf])array([ True, False,  True], dtype=bool)