# Kahan 求和算法

**Kahan 求和算法**，又称补偿求和，是一种浮点数求和方法：每次加法中被舍去的舍入误差由一个补偿变量捕获，并反馈进下一次加法，从而把随项数增长的累积误差降到基本上与项数无关。William Kahan 于 1965 年在一页纸的短文《Pracniques: Further Remarks on Reducing Truncation Errors》中发表了这一方法，载于《美国计算机学会通讯》（*Communications of the ACM*）第 8 卷第 1 期第 40 页。<sup>[1](https://dblp.org/pid/k/WilliamKahan)</sup><sup> • </sup><sup>[2](https://cpoli.github.io/mathematicskit/history/numerical_analysis_breakthroughs.html)</sup>

| 关键事实 | 详情 |
|---|---|
| 起源 | William Kahan，《Pracniques: Further Remarks on Reducing Truncation Errors》，《美国计算机学会通讯》8(1):40，1965 年<sup>[1](https://dblp.org/pid/k/WilliamKahan)</sup> |
| 机制 | 每次加法后，把丢失的低位比特精确还原为 \( c = (t - s) - y \)，并从下一项中减去<sup>[2](https://cpoli.github.io/mathematicskit/history/numerical_analysis_breakthroughs.html)</sup> |
| 误差界 | 朴素求和：\( n\varepsilon \sum \|x_i\| \)；Kahan：\( (2\varepsilon + O(\varepsilon^2)) \sum \|x_i\| \)，一阶意义上与 \( n \) 无关<sup>[3](https://munch-group.org/phasic/mathref/03_numerical_primitives.html)</sup> |
| 代价 | 每项多三次浮点运算<sup>[2](https://cpoli.github.io/mathematicskit/history/numerical_analysis_breakthroughs.html)</sup> |
| 已知弱点 | 对 \( [10^{16},\ 1.0,\ -10^{16}] \) 这类输入会静默失败，而 Neumaier 变体能恢复正确值<sup>[4](https://github.com/zcoderz/high_performance_compute/blob/main/parts/python/ch22_fp_reductions_stability/README.md)</sup> |
| 编译器风险 | `-fassociative-math`（由 `-ffast-math` 启用）之类的重结合优化会破坏该算法<sup>[5](https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html)</sup> |
| 实际性能 | 配合 SIMD 向量化与循环展开，当内存带宽成为瓶颈时，Kahan 增强的标量积几乎不比朴素版本多花代价<sup>[6](https://arxiv.org/abs/1505.02586)</sup> |

## 为什么朴素求和会损失精度

浮点加法把结果舍入到最近的可表示数。当一个较大的累加和吞掉一个小项时，小项的低位比特从累加器末端掉落，而每次加法都会重复这一损失。因此，从左到右相加 \( n \) 个数，精度损失可能与 \( n \) 成正比：朴素求和的最坏情况误差界是 \( n\varepsilon \sum_{i=1}^{n} |x_i| \)，其中 \( \varepsilon \) 是单位舍入误差，也称机器 epsilon。<sup>[2](https://cpoli.github.io/mathematicskit/history/numerical_analysis_breakthroughs.html)</sup><sup> • </sup><sup>[3](https://munch-group.org/phasic/mathref/03_numerical_primitives.html)</sup> 用相对误差表示，朴素界为 \( O(n \cdot \varepsilon) \)；当符号相反的大项几乎相消时，绝对误差可以无界增长。<sup>[7](https://github.com/algorithmica-org/algorithmica/blob/master/content/english/hpc/arithmetic/errors.md)</sup>

## 算法

Kahan 的方法保留第二个累加器 \( c \)，用来存放每一项中累加和无法表示的部分：

```
s = 0; c = 0
for i in 1..n:
    y = x[i] - c          // 第一次迭代时 c 为零
    t = s + y             // y 的低位比特在这里丢失
    c = (t - s) - y       // 精确还原丢失的部分
    s = t
```

表达式 \( (t - s) \) 消去 \( y \) 的高位部分，留下被舍入去掉的比特，符号相反；把它从下一项中减去，就把这些比特还给了和。<sup>[2](https://cpoli.github.io/mathematicskit/history/numerical_analysis_breakthroughs.html)</sup><sup> • </sup><sup>[7](https://github.com/algorithmica-org/algorithmica/blob/master/content/english/hpc/arithmetic/errors.md)</sup> 代价是每项多三次浮点运算，算上朴素循环本就执行的那两次加法，每步共六次。<sup>[2](https://cpoli.github.io/mathematicskit/history/numerical_analysis_breakthroughs.html)</sup><sup> • </sup><sup>[8](https://github.com/RiazML/math-for-llms/blob/master/10-Numerical-Methods/01-Floating-Point-Arithmetic/notes.md)</sup>

## 误差界

形式化保证针对浮点输入 \( x_1, \ldots, x_n \)，精确和为 \( S_n \)，计算和为 \( \hat{S}_n \)：<sup>[3](https://munch-group.org/phasic/mathref/03_numerical_primitives.html)</sup>

\[ |\hat{S}_n - S_n| \leq (2\varepsilon + O(\varepsilon^2)) \sum_{i=1}^{n} |x_i| \]

而朴素求和为 \( n\varepsilon \sum |x_i| + O(\varepsilon^2) \)。写成相对误差，Kahan 的界是 \( 2\varepsilon + O(n\varepsilon^2) \)：首项来自最后一次加法，\( O(n\varepsilon^2) \) 项反映补偿步骤自身的小残差。<sup>[7](https://github.com/algorithmica-org/algorithmica/blob/master/content/english/hpc/arithmetic/errors.md)</sup> 该界随 \( \sum |x_i| \) 缩放，因此在病态情形下最坏情况绝对误差仍与 \( n \) 成二次关系；一阶意义上与 \( n \) 无关，是相对误差而非绝对误差的界。<sup>[9](https://orlp.net/blog/taming-float-sums/)</sup>

北卡罗来纳州立大学的 Eric Hallman 与 Ilse C. F. Ipsen 在 2021 年的一项分析中，为补偿求和推导了一阶与二阶的确定性界和概率界，并在数值实验中发现，在一般求和、移位一般求和与补偿求和三者中，补偿求和通常是最精确的方法。<sup>[10](https://arxiv.org/abs/2107.01604)</sup>

## 变体与更强的替代方案

**Neumaier 变体。** Arnold Neumaier 1974 年发表于《应用数学与力学杂志》（*ZAMM*）的论文分析了几种求和过程的舍入误差界，包括 Kahan 与 Babuška 的方法。<sup>[11](https://onlinelibrary.wiley.com/doi/abs/10.1002/zamm.19740540106)</sup> Kahan–Babuška–Neumaier 变体在加入补偿时带一个量值判断：当当前项大于累加和时走另一分支。这补上了原方法的一个漏洞：对输入 \( [10^{16},\ 1.0,\ -10^{16}] \)（精确和为 1.0），Kahan 求和返回 0.0，因为第二步还原出的补偿恰好为零，而 Neumaier 变体返回正确的 1.0。据一份资料，该变体现在就在 Python 内置的 `sum` 中。<sup>[4](https://github.com/zcoderz/high_performance_compute/blob/main/parts/python/ch22_fp_reductions_stability/README.md)</sup><sup> • </sup><sup>[2](https://cpoli.github.io/mathematicskit/history/numerical_analysis_breakthroughs.html)</sup>

**精确求和。** Python 的 `math.fsum` 走得更远，它跟踪所有丢失的数字，使结果只带一次舍入；它比普通 `sum()` 慢，但更精确，尤其当大数值输入大部分相消时。<sup>[12](https://docs.python.org/uk/3.12/tutorial/floatingpoint.html)</sup><sup> • </sup><sup>[13](https://docs.python.org/3.11/library/math.html?highlight=math)</sup> NumPy 则使用部分成对求和，以很小的代价比朴素累加提高精度，其文档指出 `math.fsum` 是更慢但更精确的选择。<sup>[14](https://numpy.org/doc/stable/reference/generated/numpy.sum.html?highlight=numpy+average)</sup> Julia 内置的 `sum` 使用成对求和，最坏情况误差为 \( O(\log n) \)，平均情况为 \( O(\sqrt{\log n}) \)。<sup>[15](https://ocw.mit.edu/courses/18-335j-introduction-to-numerical-methods-spring-2019/906cd44ea38d0bb54e13138efd67f3a1_MIT18_335JS19_lec3-1.pdf)</sup>

**补偿带来了什么。** Julia 中补偿算法的基准测试表明，Kahan–Babuška–Neumaier 与 Ogita–Rump–Oishi 补偿求和直到和的条件数达到 \( 1/\varepsilon^2 \approx 10^{32} \) 时仍然精确，而朴素求和与成对求和在超过 \( 1/\varepsilon \approx 10^{16} \) 后已只剩噪声。实际上，简单补偿算法产生的结果，等同于用双倍工作精度做朴素求和再舍入回来。<sup>[16](https://github.com/JuliaMath/AccurateArithmetic.jl)</sup>

## 实际使用与陷阱

**编译器。** 该算法依赖运算的精确顺序。GCC 的 `-fassociative-math`（由 `-ffast-math` 和 `-Ofast` 启用）允许对浮点操作数重结合，可能重排补偿表达式，改变结果；普通 `-O` 级别不启用该选项，因为它会对依赖 IEEE 舍入行为的程序产生错误输出。<sup>[5](https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html)</sup> 另一个风险是，编译器可能识别出 \( c \) 在精确算术中恒为零，从而把循环化简为朴素标量积，使算法失效；下面的性能研究正因如此使用了手写汇编。<sup>[6](https://arxiv.org/abs/1505.02586)</sup>

**实际代价。** 埃尔朗根-纽伦堡大学的 Johannes Hofmann、Dietmar Fey、Jan Eitzinger、Georg Hager 和 Gerhard Wellein 在 Intel 处理器上对 Kahan 增强标量积的研究发现，在应用适当的底层优化（尤其是 SIMD 向量化与循环展开）后，Kahan 增强内核相比朴素标量积几乎不增加额外代价，因为任何能跑满内存带宽的代码都会把额外算术隐藏起来。<sup>[6](https://arxiv.org/abs/1505.02586)</sup> 对典型工作负载，其他报告把 Kahan 求和的开销放在个位数百分比范围。<sup>[17](https://systemhalted.in/2026/01/11/kahan-summation-java-streams/)</sup>

**并行环境。** 浮点加法不满足结合律，因此重排各项会改变结果；这是浮点值并行计算固有的。<sup>[18](https://docs.nvidia.com/cuda/archive/8.0/cuda-c-best-practices-guide/index.html)</sup> Kahan 求和因其简单、附加代价低和额外精度而被用于并行编程，而并行树归约通常比串行求和精确得多。<sup>[19](https://www.sciencedirect.com/science/article/pii/S0167819111000238)</sup><sup> • </sup><sup>[20](https://docs.nvidia.com/cuda/archive/11.0/floating-point/index.html)</sup> 该方法还超出标量：两个矩阵浮点相加的舍入误差本身就是一个浮点矩阵，因此补偿求和可直接适配矩阵求和，带一个修正项 \( C \in \mathbb{R}^{d \times d} \)。<sup>[21](https://link.springer.com/article/10.1007/s00211-025-01493-4)</sup>

## Kahan 后来的角色

William Kahan（生于 1933 年）后来成为 IEEE 754 浮点标准的主要架构师之一，并于 1989 年获得图灵奖。<sup>[22](https://www.math.utah.edu/~feldman/teaching_files/F18/natwo.pdf)</sup> 在需要长求和的精确性的地方，补偿求和及其同类方法已是标准做法。<sup>[2](https://cpoli.github.io/mathematicskit/history/numerical_analysis_breakthroughs.html)</sup>

## References

1. [dblp: William Kahan (bibliography listing Comm. ACM 8(1):40, 1965)](https://dblp.org/pid/k/WilliamKahan)
2. [Breakthroughs in Numerical Analysis, mathematicskit documentation](https://cpoli.github.io/mathematicskit/history/numerical_analysis_breakthroughs.html)
3. [Numerical Primitives, Mathematical Reference (Theorem 4.1, Kahan summation error bound)](https://munch-group.org/phasic/mathref/03_numerical_primitives.html)
4. [Floating-point reductions and stability worked examples (Kahan vs. Neumaier)](https://github.com/zcoderz/high_performance_compute/blob/main/parts/python/ch22_fp_reductions_stability/README.md)
5. [Optimize Options, Using the GNU Compiler Collection (GCC)](https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html)
6. [Hofmann et al., Performance analysis of the Kahan-enhanced scalar product on current multicore processors, arXiv:1505.02586](https://arxiv.org/abs/1505.02586)
7. [Algorithmica: Floating-point errors, Kahan summation](https://github.com/algorithmica-org/algorithmica/blob/master/content/english/hpc/arithmetic/errors.md)
8. [math-for-llms notes: floating-point arithmetic, Kahan summation proof](https://github.com/RiazML/math-for-llms/blob/master/10-Numerical-Methods/01-Floating-Point-Arithmetic/notes.md)
9. [Taming Floating-Point Sums, orlp.net](https://orlp.net/blog/taming-float-sums/)
10. [Hallman & Ipsen, Deterministic and Probabilistic Error Bounds for Floating Point Summation Algorithms, arXiv:2107.01604](https://arxiv.org/abs/2107.01604)
11. [Neumaier (1974), Rundungsfehleranalyse einiger Verfahren zur Summation endlicher Summen, ZAMM 54:39-51](https://onlinelibrary.wiley.com/doi/abs/10.1002/zamm.19740540106)
12. [Python tutorial: Floating-Point Arithmetic, Issues and Limitations](https://docs.python.org/uk/3.12/tutorial/floatingpoint.html)
13. [Python math module documentation (math.fsum)](https://docs.python.org/3.11/library/math.html?highlight=math)
14. [numpy.sum documentation](https://numpy.org/doc/stable/reference/generated/numpy.sum.html?highlight=numpy+average)
15. [MIT 18.335J, Notes on the accuracy of naive summation](https://ocw.mit.edu/courses/18-335j-introduction-to-numerical-methods-spring-2019/906cd44ea38d0bb54e13138efd67f3a1_MIT18_335JS19_lec3-1.pdf)
16. [JuliaMath/AccurateArithmetic.jl documentation](https://github.com/JuliaMath/AccurateArithmetic.jl)
17. [Part 7: Kahan Summation, A Better sum() for Java Streams, SystemHalted](https://systemhalted.in/2026/01/11/kahan-summation-java-streams/)
18. [CUDA Best Practices Guide, Numerical Accuracy and Precision](https://docs.nvidia.com/cuda/archive/8.0/cuda-c-best-practices-guide/index.html)
19. [In search of numerical consistency in parallel programming, Parallel Computing](https://www.sciencedirect.com/science/article/pii/S0167819111000238)
20. [CUDA Floating Point and IEEE 754 documentation](https://docs.nvidia.com/cuda/archive/11.0/floating-point/index.html)
21. [Summing divergent matrix series, Numerische Mathematik (2025)](https://link.springer.com/article/10.1007/s00211-025-01493-4)
22. [University of Utah, Floating-Point Arithmetic lecture notes (Kahan biography)](https://www.math.utah.edu/~feldman/teaching_files/F18/natwo.pdf)

---
*Initially written Sep 17, 2026 · Reviewed: Sep 17, 2026; Sep 20, 2026; Sep 30, 2026; Oct 15, 2026 · Edited: Sep 20, 2026; Sep 30, 2026; Oct 11, 2026; Oct 15, 2026; Oct 25, 2026 · Last review: Oct 15, 2026*

Topic: 物质世界与数学 › 数学与统计学 › 数与代数 › Linear and multilinear algebra › Numerical linear algebra › Conditioning, error analysis, and stability

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/kahan-summation-algorithm

English original: https://www.edgepedia.org/kahan-summation-algorithm
