The Float Precision Trap

Medium ⏱ 12 min 62% acceptance ★★★★★ 4.7
Classic gotcha: 0.1 + 0.2 == 0.3 is False in Python due to binary floating-point representation. Write a function nearly_equal(a, b, tolerance=1e-9) that returns True if two floats a and b are equal within tolerance, and False otherwise. This is the correct way to compare floats.

Examples

Example 1
Input
nearly_equal(0.1 + 0.2, 0.3)
Output
True
Explanation

The tiny representational error is within tolerance.

Example 2
Input
nearly_equal(1.0, 1.5)
Output
False
Explanation

Difference of 0.5 exceeds tolerance.

Constraints

  • `a`, `b` are floats.
  • `tolerance` defaults to 1e-9 but callers may override it.

Topics

Variables & Data Typesfloating point

Companies

Deutsche BankGoldman Sachs

Hints

Hint 1

Compare `abs(a - b)` against tolerance.

Hint 2

Do not use `==` directly on the floats.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.