python data_error ai_generated true

AssertionError: assert 0.1 + 0.2 == 0.3; 0.30000000000000004 != 0.3

ID: python/pytest-assert-approx-equality

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2025-08-18First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.10 active

Root Cause

Floating-point arithmetic precision issues cause equality assertions to fail when comparing computed floats to expected values.

generic

中文

浮点算术精度问题导致在将计算出的浮点数与预期值进行比较时,相等性断言失败。

Workarounds

  1. 95% success
    Use pytest.approx: assert 0.1 + 0.2 == pytest.approx(0.3, rel=1e-9) or abs=1e-12
  2. 90% success
    Use math.isclose: assert math.isclose(0.1 + 0.2, 0.3, rel_tol=1e-9)

Dead Ends

Common approaches that don't work:

  1. 50% fail

    Rounding the result to a fixed number of decimal places may work for some cases but can mask precision errors in edge cases.

  2. 40% fail

    Using assertAlmostEqual with a default tolerance may still fail if the tolerance is too small.