The math.isinf(x) function checks whether a numeric value x is infinite (either positive infinity +inf or negative infinity -inf). It returns True if the number is infinite, and False for all finite numbers, zeros, and Not-a-Number (nan) values.
Distinguishing Direction: Because math.isinf() returns True for both signs, test x > 0 for positive infinity and x < 0 for negative infinity.
The math.isinf() function belongs to Python's built-in math module:
import math
math.isinf(x)
| Component | Type | Description |
|---|---|---|
x |
float or int |
Required. The numeric value to test. |
| Return Value | bool |
True if x is +inf or -inf; False otherwise. |
TypeError |
Exception | Raised when x is non-numeric (e.g. strings, lists, dictionaries, None). |
In Python, infinite floating-point values arise from two primary mechanisms:
"inf", "+inf", or "-inf" to floats.import math
# 1. Direct infinity literals
print("isinf(float('inf')): ", math.isinf(float('inf'))) # True
print("isinf(float('-inf')):", math.isinf(float('-inf'))) # True
# 2. Arithmetic overflow beyond 1.79e308
huge_val = 1e308 * 2.0
print("huge_val value: ", huge_val) # inf
print("isinf(huge_val): ", math.isinf(huge_val)) # True
# 3. Finite numbers and zeros return False
print("isinf(0.0): ", math.isinf(0.0)) # False
print("isinf(-999999.5): ", math.isinf(-999999.5)) # False
print("isinf(nan): ", math.isinf(float('nan'))) # False (NaN is not infinite)
Output:
isinf(float('inf')): True
isinf(float('-inf')): True
huge_val value: inf
isinf(huge_val): True
isinf(0.0): False
isinf(-999999.5): False
isinf(nan): False
1.0 / 0.0 raises a ZeroDivisionError rather than silently returning inf. If you wish to represent unbounded limits, catch the exception and assign float('inf') explicitly.
Because math.isinf() returns True for both +inf and -inf, determining the sign requires an additional relational comparison or sign check with math.copysign():
import math
def classify_infinity(val):
if not math.isinf(val):
return "Finite or NaN"
return "Positive Infinity (+inf)" if val > 0 else "Negative Infinity (-inf)"
print("+inf classification:", classify_infinity(float('inf')))
print("-inf classification:", classify_infinity(float('-inf')))
print("100 classification:", classify_infinity(100.0))
Output:
+inf classification: Positive Infinity (+inf)
-inf classification: Negative Infinity (-inf)
100 classification: Finite or NaN
Python adheres to IEEE 754 standard arithmetic rules when performing operations involving infinity:
| Operation | Result | Mathematical Rule |
|---|---|---|
inf + 50.0 |
inf |
Adding any finite number to infinity yields infinity. |
inf * -2.0 |
-inf |
Multiplying by a negative finite number flips the sign of infinity. |
1.0 / inf |
0.0 |
Reciprocal of positive infinity is positive zero. |
1.0 / -inf |
-0.0 |
Reciprocal of negative infinity is signed negative zero. |
inf - inf |
nan |
Subtracting infinity from infinity is an indeterminate form. |
inf / inf |
nan |
Dividing infinity by infinity is an indeterminate form. |
0.0 * inf |
nan |
Zero multiplied by infinity is an indeterminate form. |
Understanding how the three classification functions in Python's math module partition all numeric values:
Numeric Value x |
math.isinf(x) |
math.isnan(x) |
math.isfinite(x) |
|---|---|---|---|
float('inf') |
True | False | False |
float('-inf') |
True | False | False |
float('nan') |
False | True | False |
0.0 / -0.0 |
False | False | True |
1e308 |
False | False | True |
In machine learning model training, deep neural networks, and physics simulations, numerical instability can lead to exploding gradients. When weights or forces diverge, values overflow to +inf or -inf, instantly corrupting the entire model.
Build an optimizer gradient sanitizer function that inspects a list of parameter gradients, detects infinite values using math.isinf(), clips them to a maximum threshold while preserving their direction, and flags whether divergence occurred:
import math
def sanitize_and_clip_gradients(gradients, clip_threshold=100.0):
"""
Inspects gradients for infinite values.
Clips infinite or out-of-bound values to [-clip_threshold, +clip_threshold].
Returns (clipped_gradients, had_infinities).
"""
if not isinstance(gradients, (list, tuple)):
raise TypeError("Gradients must be a list or tuple.")
sanitized = []
found_inf = False
for g in gradients:
if math.isnan(g):
sanitized.append(0.0) # Reset NaN to zero
elif math.isinf(g):
found_inf = True
# Clip to +/- clip_threshold based on direction
clipped = math.copysign(clip_threshold, g)
sanitized.append(clipped)
else:
# Finite value: clamp within bounds
clamped = max(-clip_threshold, min(clip_threshold, float(g)))
sanitized.append(clamped)
return (sanitized, found_inf)
# Test Data
raw_grads = [2.5, float('inf'), -15.0, float('-inf'), 120.0]
clean_grads, diverged = sanitize_and_clip_gradients(raw_grads, clip_threshold=50.0)
# Unit Assertions
assert diverged is True
assert clean_grads[0] == 2.5
assert clean_grads[1] == 50.0 # +inf clipped to +50.0
assert clean_grads[2] == -15.0
assert clean_grads[3] == -50.0 # -inf clipped to -50.0
assert clean_grads[4] == 50.0 # 120.0 clamped to +50.0
# Normal batch with zero infinities
normal_grads = [1.0, -2.0, 3.0]
res_normal, had_inf = sanitize_and_clip_gradients(normal_grads, 10.0)
assert had_inf is False
assert res_normal == [1.0, -2.0, 3.0]
print("Original gradients: ", raw_grads)
print("Clipped gradients: ", clean_grads)
print("All gradient sanitizer assertions passed successfully!")
Open in Google Colab View on GitHub
Run all math.isinf() examples interactively, test IEEE 754 infinity arithmetic, distinguish positive/negative infinities, and run the exploding gradient sanitizer in Google Colab.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.