isinf() returns True specifically for inf and -inf, and False for every finite number and for nan — it doesn't distinguish between positive and negative infinity by default, though np.isposinf() and np.isneginf() exist for that finer distinction if needed. Infinite values typically arise from dividing a nonzero number by zero, or from an operation like np.exp() overflowing for a very large input, so isinf() is a common diagnostic check after computations prone to those specific failure modes.
1Understanding np.isinf()
isinf() returns True specifically for inf and -inf, and False for every finite number and for nan — it doesn't distinguish between positive and negative infinity by default, though np.isposinf() and np.isneginf() exist for that finer distinction if needed. Infinite values typically arise from dividing a nonzero number by zero, or from an operation like np.exp() overflowing for a very large input, so isinf() is a common diagnostic check after computations prone to those specific failure modes.
isinf() treats positive and negative infinity the same by default — use np.isposinf()/np.isneginf() specifically when you need to distinguish which direction the overflow happened in, rather than just detecting that it happened.
import numpy as np
arr = np.array([1.0, np.inf, -np.inf, 5.0])
print(np.isinf(arr))2Practical Example
Here is a real-world application of np.isinf() showing how it is used in production NumPy code.
import numpy as np
result = np.array([1.0, 5.0]) / np.array([2.0, 0.0])
print(result)
print(np.isinf(result))3Best Practices
Follow these guidelines when working with np.isinf():
1. Check for inf values specifically with isinf() after divisions or exponentials that could plausibly overflow
2. Use np.isposinf()/np.isneginf() instead of isinf() when the direction, positive vs negative infinity, of the overflow actually matters
3. Combine isinf() with np.where() to replace infinite values with a safe substitute, like the array's maximum finite value
Tip: isinf() treats positive and negative infinity the same by default — use np.isposinf()/np.isneginf() specifically when you need to distinguish which direction the overflow happened in, rather than just detecting that it happened.
import numpy as np
arr = np.array([1.0, np.inf, -np.inf, 5.0])
print(np.isinf(arr))