python data_error ai_generated true

AssertionError: assert 0.1 + 0.2 == 0.3 (pytest.approx used incorrectly)

ID: python/pytest-approx-float-comparison-error

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-05-30First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.9 active
3.10 active

Root Cause

Floating point arithmetic leads to precision issues; using '==' directly fails, and pytest.approx must be applied to both sides or used as a context.

generic

中文

浮点运算导致精度问题;直接使用 '==' 会失败,并且必须将 pytest.approx 应用于两侧或作为上下文使用。

Workarounds

  1. 95% success Use pytest.approx to compare floating point values within tolerance.
    assert 0.1 + 0.2 == pytest.approx(0.3)
  2. 90% success Specify relative tolerance using pytest.approx with rel parameter.
    assert result == pytest.approx(expected, rel=1e-9)

Dead Ends

Common approaches that don't work:

  1. Using round() on both values to compare 60% fail

    Rounding can still introduce errors if the rounding precision is not chosen carefully.

  2. Comparing with == after converting to Decimal 50% fail

    Decimal conversion may not be accurate if the original values are floats.