python
data_error
ai_generated
true
AssertionError: assert 0.30000000000000004 == 0.3 E + 其中 0.30000000000000004 = 0.1 + 0.2
AssertionError: assert 0.30000000000000004 == 0.3 E + where 0.30000000000000004 = 0.1 + 0.2
ID: python/pytest-assertion-approx-float
80%修复率
90%置信度
0证据数
2025-02-03首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
根因分析
二进制浮点表示无法精确表示 0.3;直接对浮点数使用相等比较不可靠。
English
Binary floating-point representation cannot represent 0.3 exactly; direct equality on floats is unreliable.
解决方案
-
98% 成功率
import pytest def test_sum(): assert 0.1 + 0.2 == pytest.approx(0.3) assert [0.1, 0.2] == pytest.approx([0.1, 0.2]) -
95% 成功率
import math def test_sum(): assert math.isclose(0.1 + 0.2, 0.3, rel_tol=1e-9, abs_tol=1e-12)
无效尝试
常见但无效的做法:
-
50% 失败
Works for some values but fails for very large or very small magnitudes; not a general solution.
-
70% 失败
String representations vary across Python versions and locales; brittle.