python type_error ai_generated true

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

AssertionError: assert 0.1 + 0.2 == 0.3 + where 0.1 + 0.2 = 0.30000000000000004

ID: python/pytest-approx-comparison-fail

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2025-04-10首次发现

版本兼容性

版本状态引入弃用备注
7.0.0 active
8.0.0 active

根因分析

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

English

Floating-point arithmetic precision issues cause the sum of 0.1 and 0.2 to be slightly off from 0.3, leading to a failed equality assertion.

generic

解决方案

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

无效尝试

常见但无效的做法:

  1. Rounding the result to a fixed number of decimal places 60% 失败

    This may mask real precision issues in other calculations and is not a general solution.

  2. Using assert 0.1 + 0.2 == 0.3 with a tolerance check manually 40% 失败

    This is error-prone and less readable than using pytest.approx.