python
data_error
ai_generated
true
AssertionError: assert 0.30000000000000004 == 0.3 E + where 0.30000000000000004 = 0.1 + 0.2
ID: python/pytest-assertion-approx-float
80%Fix Rate
90%Confidence
0Evidence
2025-02-03First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
Root Cause
Binary floating-point representation cannot represent 0.3 exactly; direct equality on floats is unreliable.
generic中文
二进制浮点表示无法精确表示 0.3;直接对浮点数使用相等比较不可靠。
Workarounds
-
98% success
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% success
import math def test_sum(): assert math.isclose(0.1 + 0.2, 0.3, rel_tol=1e-9, abs_tol=1e-12)
Dead Ends
Common approaches that don't work:
-
50% fail
Works for some values but fails for very large or very small magnitudes; not a general solution.
-
70% fail
String representations vary across Python versions and locales; brittle.