python runtime_error ai_generated true

断言错误:断言 0.1 + 0.2 == 0.3

AssertionError: assert 0.1 + 0.2 == 0.3

ID: python/assertionerror-assert-approx-equal

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

版本兼容性

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

根因分析

浮点运算精度问题导致总和与预期值略有偏差。

English

Floating-point arithmetic precision issues cause the sum to be slightly off from expected value.

generic

解决方案

  1. 95% 成功率 Use pytest.approx for approximate comparison
    assert 0.1 + 0.2 == pytest.approx(0.3)
  2. 90% 成功率 Use math.isclose with tolerance
    import math; assert math.isclose(0.1 + 0.2, 0.3, rel_tol=1e-9)

无效尝试

常见但无效的做法:

  1. Using round() on both sides 60% 失败

    round() may still produce different results due to floating-point representation.

  2. Multiplying by a factor to avoid decimals 40% 失败

    Does not eliminate the underlying precision issue; may introduce new errors.