python runtime_error ai_generated true

AssertionError: assert 0.1 + 0.2 == 0.3

ID: python/assertionerror-assert-approx-equal

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2025-06-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8 active
3.9 active
3.10 active

Root Cause

Floating-point arithmetic precision issues cause the sum to be slightly off from expected value.

generic

中文

浮点运算精度问题导致总和与预期值略有偏差。

Workarounds

  1. 95% success Use pytest.approx for approximate comparison
    assert 0.1 + 0.2 == pytest.approx(0.3)
  2. 90% success Use math.isclose with tolerance
    import math; assert math.isclose(0.1 + 0.2, 0.3, rel_tol=1e-9)

Dead Ends

Common approaches that don't work:

  1. Using round() on both sides 60% fail

    round() may still produce different results due to floating-point representation.

  2. Multiplying by a factor to avoid decimals 40% fail

    Does not eliminate the underlying precision issue; may introduce new errors.