Handling Infinity (inf) and Not a Number (nan) in Python: float and math module

Python’s float type can represent special states like “Infinity” and “Not a Number” in addition to standard numbers like 3.14 or -0.5. These are used in mathematical calculations (like division by zero attempts) or when handling missing values in data analysis.

This article explains how to create inf (infinity) and nan (Not a Number), how they behave in calculations, and how to check for them.


目次

Creating and Properties of Infinity (inf)

Infinity can be created by passing the string 'inf' to the float constructor.

Python

# Positive Infinity
pos_inf = float('inf')
# Negative Infinity
neg_inf = float('-inf')

print(f"Positive Infinity: {pos_inf}")
print(f"Negative Infinity: {neg_inf}")
print(f"Type: {type(pos_inf)}")

Output:

Positive Infinity: inf
Negative Infinity: -inf
Type: <class 'float'>

If you import the math module, you can also use math.inf directly.

Operations with inf

Infinity remains infinity in most operations.

# Infinity + Number = Infinity
print(f"inf + 10000 = {pos_inf + 10000}")

# Infinity * Number = Infinity
print(f"inf * 500 = {pos_inf * 500}")

# Infinity / Number = Infinity
print(f"inf / 123 = {pos_inf / 123}")

# Infinity + Infinity = Infinity
print(f"inf + inf = {pos_inf + pos_inf}")

Output:

inf + 10000 = inf
inf * 500 = inf
inf / 123 = inf
inf + inf = inf

Creating and Properties of Not a Number (nan)

“Not a Number” can be created with float('nan'). nan is used to indicate that the result of a calculation is undefined as a real number.

When nan occurs

nan occurs in calculations that are mathematically “indeterminate forms”.

# 0.0 / 0.0
nan_val_1 = 0.0 / 0.0

# inf - inf
nan_val_2 = float('inf') - float('inf')

# inf / inf
nan_val_3 = float('inf') / float('inf')

print(f"0.0 / 0.0 = {nan_val_1}")
print(f"inf - inf = {nan_val_2}")
print(f"inf / inf = {nan_val_3}")

Output:

0.0 / 0.0 = nan
inf - inf = nan
inf / inf = nan

Operations with nan (Propagation)

nan has a property called “propagation”. Almost any operation involving nan results in nan.

base_nan = float('nan')
print(f"nan + 50 = {base_nan + 50}")
print(f"nan * 0 = {base_nan * 0}") # Even multiplying by 0 results in nan

Output:

nan + 50 = nan
nan * 0 = nan

How to Check for inf and nan

Since inf and nan often require special handling in data processing, it is important to know how to identify them correctly. Use the math module for checking.

import math

val_inf = float('inf')
val_nan = float('nan')
val_num = 100.0

# isinf() : Check if it is infinity
print(f"math.isinf({val_inf}): {math.isinf(val_inf)}") # True
print(f"math.isinf({val_num}): {math.isinf(val_num)}") # False

# isnan() : Check if it is Not a Number
print(f"math.isnan({val_nan}): {math.isnan(val_nan)}") # True
print(f"math.isnan({val_inf}): {math.isnan(val_inf)}") # False

Critical Note on Checking nan

Never use the == operator to check for nan. nan has a special property where it is not equal to itself (it returns False).

test_nan = float('nan')

# Incorrect check using '=='
print(f"test_nan == float('nan') : {test_nan == float('nan')}") # False
print(f"test_nan == test_nan : {test_nan == test_nan}")     # False

To reliably check if a value is nan, always use math.isnan().


Practical Example: Safe Data Aggregation

If a data list contains inf or nan, functions like sum() will not work as intended. Here is an example of processing data while excluding these values.

import math

def calculate_safe_average(data_list):
    """
    Calculate average excluding inf and nan
    """
    total = 0
    count = 0
    for value in data_list:
        # Check for inf or nan and skip
        if math.isinf(value) or math.isnan(value):
            print(f"Skipping: {value}")
            continue
        
        total += value
        count += 1
        
    if count == 0:
        return 0.0 # Or return nan
        
    return total / count

# --- Execution ---
raw_data = [15.5, 20.0, float('inf'), 10.0, float('nan'), 5.5, float('-inf')]
average = calculate_safe_average(raw_data)

print(f"Raw Data: {raw_data}")
print(f"Safe Average: {average}")

Output:

Skipping: inf
Skipping: nan
Skipping: -inf
Raw Data: [15.5, 20.0, inf, 10.0, nan, 5.5, -inf]
Safe Average: 12.75

Summary

  • Create infinity with float('inf') or math.inf.
  • Create Not a Number with float('nan') or math.nan. It also results from indeterminate forms like 0/0 or inf-inf.
  • Use math.isinf() and math.isnan() to check for these values.
  • nan == nan is False. Never use == to check for nan.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次