Course contentsShow
← Python
Lesson 34 of 1,0601. Foundations and EnvironmentFree lesson

Floating-Point Approximation and Safe Comparisons with math.isclose

Explain binary floating-point approximation, identify NaN and infinity with math helpers, and compare finite values safely using math.isclose tolerances.

In this lesson, you will learn why computers struggle to represent some decimal numbers exactly and how to use math.isclose to compare them reliably.

The Floating-Point Problem

Computers store numbers in binary (base-2). While integers are easy to represent, many decimal numbers (like 0.1) cannot be written as a finite binary fraction. This leads to tiny rounding errors. Because of this, Python’s calculation might result in a number that is "extremely close" to what you expect, but not technically identical.

Try running this:

import math

result = 0.1 + 0.1 + 0.1
print(result == 0.3)  # This prints False!

Even though result looks like 0.3, it is actually stored as 0.30000000000000004. Because of this invisible gap, standard equality checks (==) will fail.

Safe Comparisons with math.isclose

Instead of checking for exact equality, we check if two numbers are "close enough." The math.isclose() function handles this by checking if the difference between two numbers is within a tiny, acceptable range.

import math

# Using isclose to compare safely
print(math.isclose(0.1 + 0.1 + 0.1, 0.3))  # This prints True

Identifying Special Values

Sometimes, calculations result in non-finite values. You can use math module tools to verify these special states:

  • math.isnan(x): Returns True if x is "Not a Number" (often the result of an impossible operation like 0/0).
  • math.isinf(x): Returns True if x is positive or negative infinity (often the result of dividing a large number by zero).

By using math.isclose for comparisons and checking for NaN or infinity when necessary, you ensure your programs handle floating-point math without being tripped up by tiny, hardware-based rounding artifacts.

Key Takeaway: Because floating-point numbers are approximations, always use math.isclose() instead of == when comparing decimal calculations to ensure your logic remains accurate.