python data_error ai_generated true

断言错误:断言 0.1 + 0.2 == 0.3;0.30000000000000004 != 0.3

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

ID: python/pytest-assert-approx-equality

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

版本兼容性

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

根因分析

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

English

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

generic

解决方案

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

无效尝试

常见但无效的做法:

  1. 50% 失败

    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% 失败

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