python
data_error
ai_generated
true
AssertionError: assert 0.30000000000000004 == 0.3 + where 0.30000000000000004 = 0.1 + 0.2
ID: python/pytest-assertion-approx-strict
80%Fix Rate
92%Confidence
0Evidence
2024-01-08First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
Root Cause
Floating-point arithmetic produces small representation errors. Direct equality on floats is unreliable; pytest provides pytest.approx for this purpose.
generic中文
浮点运算会产生小的表示误差。浮点数直接相等比较不可靠;pytest 提供了 pytest.approx 用于此场景。
Workarounds
-
98% success
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% success
For numpy arrays: import numpy as np np.testing.assert_allclose(a, b, rtol=1e-6)
Dead Ends
Common approaches that don't work:
-
55% fail
Works for this case but fails for very large/small magnitudes and hides genuine precision bugs.
-
50% fail
Default rel_tol=1e-9 may be too strict for accumulated errors or too loose for scientific tests.