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
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.
解决方案
-
95% 成功率 Use pytest.approx for approximate comparison
assert 0.1 + 0.2 == pytest.approx(0.3)
-
90% 成功率 Use math.isclose with tolerance
import math; assert math.isclose(0.1 + 0.2, 0.3, rel_tol=1e-9)
无效尝试
常见但无效的做法:
-
Using round() on both sides
60% 失败
round() may still produce different results due to floating-point representation.
-
Multiplying by a factor to avoid decimals
40% 失败
Does not eliminate the underlying precision issue; may introduce new errors.