python data_error ai_generated true

断言错误:assert 0.1 + 0.2 == 0.3(pytest.approx 使用不正确)

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

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

其他格式: JSON · Markdown 中文 · English
80%修复率
87%置信度
0证据数
2024-05-30首次发现

版本兼容性

版本状态引入弃用备注
3.9 active
3.10 active

根因分析

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

English

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

解决方案

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

无效尝试

常见但无效的做法:

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

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

  2. Comparing with == after converting to Decimal 50% 失败

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