python
data_error
ai_generated
true
AssertionError: assert 0.30000000000000004 == 0.3 + 其中 0.30000000000000004 = 0.1 + 0.2
AssertionError: assert 0.30000000000000004 == 0.3 + where 0.30000000000000004 = 0.1 + 0.2
ID: python/pytest-assertion-approx-strict
80%修复率
92%置信度
0证据数
2024-01-08首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
根因分析
浮点运算会产生小的表示误差。浮点数直接相等比较不可靠;pytest 提供了 pytest.approx 用于此场景。
English
Floating-point arithmetic produces small representation errors. Direct equality on floats is unreliable; pytest provides pytest.approx for this purpose.
解决方案
-
98% 成功率
Use pytest.approx: from pytest import approx assert 0.1 + 0.2 == approx(0.3) assert result == approx(expected, rel=1e-6, abs=1e-9)
-
95% 成功率
For numpy arrays: import numpy as np np.testing.assert_allclose(a, b, rtol=1e-6)
无效尝试
常见但无效的做法:
-
55% 失败
Works for this case but fails for very large/small magnitudes and hides genuine precision bugs.
-
50% 失败
Default rel_tol=1e-9 may be too strict for accumulated errors or too loose for scientific tests.