python type_error ai_generated true

AssertionError: assert 0.1 + 0.2 == 0.3 + where 0.1 + 0.2 = 0.30000000000000004

ID: python/pytest-approx-comparison-fail

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
7.0.0 active
8.0.0 active

Root Cause

Floating-point arithmetic precision issues cause the sum of 0.1 and 0.2 to be slightly off from 0.3, leading to a failed equality assertion.

generic

中文

浮点运算精度问题导致0.1和0.2的和与0.3略有偏差,导致相等性断言失败。

Workarounds

  1. 95% success Use pytest.approx for floating-point comparisons
    from pytest import approx
    assert 0.1 + 0.2 == approx(0.3)
    This uses a default relative tolerance of 1e-6.
  2. 90% success Specify a custom tolerance with approx
    assert 0.1 + 0.2 == approx(0.3, rel=1e-9, abs=1e-12)
    This allows fine-grained control over the comparison.

Dead Ends

Common approaches that don't work:

  1. Rounding the result to a fixed number of decimal places 60% fail

    This may mask real precision issues in other calculations and is not a general solution.

  2. Using assert 0.1 + 0.2 == 0.3 with a tolerance check manually 40% fail

    This is error-prone and less readable than using pytest.approx.