# 断言错误：断言 0.1 + 0.2 == 0.3
 + 其中 0.1 + 0.2 = 0.30000000000000004

- **ID:** `python/pytest-approx-comparison-fail`
- **领域:** python
- **类别:** type_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

浮点运算精度问题导致0.1和0.2的和与0.3略有偏差，导致相等性断言失败。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 7.0.0 | active | — | — |
| 8.0.0 | active | — | — |

## 解决方案

1. **Use pytest.approx for floating-point comparisons** (95% 成功率)
   ```
   from pytest import approx
assert 0.1 + 0.2 == approx(0.3)
This uses a default relative tolerance of 1e-6.
   ```
2. **Specify a custom tolerance with approx** (90% 成功率)
   ```
   assert 0.1 + 0.2 == approx(0.3, rel=1e-9, abs=1e-12)
This allows fine-grained control over the comparison.
   ```

## 无效尝试

- **Rounding the result to a fixed number of decimal places** — This may mask real precision issues in other calculations and is not a general solution. (60% 失败率)
- **Using assert 0.1 + 0.2 == 0.3 with a tolerance check manually** — This is error-prone and less readable than using pytest.approx. (40% 失败率)
