Python Float Infinity: Creation, Checks, and Pitfalls
python float infinity: Learn how to create and test Python float infinity, understand its arithmetic and comparison behavior, and avoid serialization and conversion pi...
Python represents positive and negative infinity as float values. When a computation exceeds the largest finite float, such as 1e308 * 10, Python returns inf instead of raising an exception. Working with python float infinity means knowing how to create it, test for it, and predict how it behaves in arithmetic, comparisons, and serialization.
Creating Infinity in Python
The most explicit way to create infinity is with the float constructor:
positive_inf = float('inf') negative_inf = float('-inf')
Both values are instances of float. The math module also exposes math.inf, which is the same value as float('inf'). You can use either form; float('inf') is more common because it requires no import.
import math assert math.inf == float('inf')
The constructor accepts case-insensitive variants like 'Infinity' and 'inf', but 'inf' is the standard spelling used across Python codebases.
Checking Whether a Float Is Infinite
To test whether a value is infinite, use math.isinf(). It returns True for both positive and negative infinity.
import math value = float('-inf') print(math.isinf(value)) # True
Comparing directly to float('inf') works only for positive infinity:
value = float('-inf') print(value == float('inf')) # False
So math.isinf() is the correct general check. If you need to distinguish sign, compare the value to 0 or use math.copysign to extract the sign bit.
Arithmetic Behavior of Infinity
Infinity follows IEEE 754 rules. Adding a finite number to infinity yields infinity; subtracting infinity from infinity yields nan.
| Operation | Result |
|---|---|
float('inf') + 1 | inf |
float('inf') * 2 | inf |
float('inf') / float('inf') | nan |
1 / float('inf') | 0.0 |
float('inf') - float('inf') | nan |
These results are deterministic and consistent across Python versions that use IEEE 754 doubles. When you see nan in a calculation, trace back to operations that involve infinity with itself or with zero.
Comparisons and Sorting With Infinity
Infinity compares greater than every finite float, and negative infinity compares less than every finite float. This makes infinity useful as a sentinel value for algorithms that need an upper bound.
values = [3.5, float('-inf'), 2.0, float('inf')] print(sorted(values)) # [-inf, 2.0, 3.5, inf]
Be careful with nan: nan compares unordered, so inf > nan is False and nan > inf is also False. If your data can contain nan, filtering it out before sorting avoids unpredictable ordering.
Infinity in Serialization and Data Exchange
The JSON format does not define infinity. Python's json module, by default, writes Infinity and -Infinity as bare tokens:
import json print(json.dumps(float('inf'))) # Infinity
This output is not valid strict JSON. Many JavaScript parsers accept it, but others reject it. If you need standards-compliant JSON, set allow_nan=False:
json.dumps(float('inf'), allow_nan=False) # raises ValueError
For data exchange, decide explicitly how to represent infinity: either convert it to null, to a string like "Infinity", or reject it before serialization. The same concern applies to databases that do not support IEEE 754 infinity.
Performance and Memory Considerations
An infinity value occupies the same memory as any other float in Python, because it is just a double-precision value with a special exponent pattern. Arithmetic operations involving infinity are handled by the CPU's floating-point unit; there is no Python-level overhead beyond the normal float operation cost. The main performance risk is not the value itself but the checks you add around it. Using math.isinf() is a single C-level call and is faster than a Python-level comparison chain. If you are processing large arrays, prefer vectorized operations from libraries like NumPy, which handle infinity checks in compiled code rather than in a Python loop.
Common Pitfalls and How to Avoid Them
One common mistake is converting infinity to an integer. int(float('inf')) raises OverflowError, because there is no integer representation of infinity. Similarly, round(float('inf')) raises OverflowError. If your code might receive infinity, guard conversions with math.isfinite():
import math def to_int_safe(value): if not math.isfinite(value): return None return int(value)
Another pitfall is using float('inf') as a default argument for a maximum value. That is often intentional, but if the algorithm later compares results to that default, make sure the comparison direction is correct. For example, min() with an initial inf works as expected, but max() with -inf is the right sentinel.
Finally, remember that float('inf') == float('inf') is True, but float('nan') == float('nan') is False. Do not use equality to check for infinity when math.isinf() is available and clearer.