Skip to content

Floating-点 Precision 错误

快速摘要

你的 decimal calculation gives result 如 0.30000000000000004 相反 的 0.3 — 基本 limitation 的 floating-点 math.

为什么发生

  • 一些 decimal 分数 cannot 是 represented 精确地 in binary

  • Accumulated rounding 错误 in repeated calculations

  • Comparing floating-点 值 使用 ===

最小示例

✗ 错误代码
console.log(0.1 + 0.2 === 0.3); // false!
console.log(0.1 + 0.2); // 0.30000000000000004
✓ 修复代码
const result = 0.1 + 0.2;
console.log(Math.abs(result - 0.3) < 1e-10); // true
console.log(Math.round(result * 100) / 100); // 0.3

0.1 and 0.2 cannot 是 represented 精确地 in binary, 所以 它们的 总和 有 tiny 错误. Using tolerance comparison or rounding fixes issue.

如何诊断

  • Print result 使用 完整 precision 到 see tiny 错误

  • 检查 如果 comparisons 失败 due 到 tiny differences

  • Use 数字.EPSILON 到 理解 precision 限制

如何修复

  • Round results 到 fixed 数字 的 decimal 位置: Math.round(x * 100) / 100

  • Use tolerance for comparisons: Math.abs(- b) < 0.0001

  • Use integer arithmetic or decimal 库 for financial calculations

如何预防

  • 从不 compare floats 使用 === — use tolerance 检查

  • Round results 之前 displaying 它们 到 用户

相关资源

相关术语

相关课程

← 返回语言