sum of small double numbers c++(小双数的总和c ++)
问题描述
假设我们在 c++.如果我们按顺序计算这个数组中数字的总和,例如
Assume that we have an array of small (about 10^(-15)
) double numbers in c++. If we calculate the sum of numbers in this array sequentially, for example
double sum = 0;
for (int i = 0; i < n; i++) sum+=array[i];
我们得到一些值x
.
但是,如果我们将一个数组分成若干部分,然后计算每个部分的总和,然后将所有部分总和相加,我们会得到一个值 x2
,它接近于 x
但不完全是 x
.所以我在计算总和时失去了准确性.
But if we divide an array into some parts and then calculate the sum in each part and after this we add all the partial sums together we get some value x2
, which is close to x
but not exactly x
. So I have lost accruacy in calculating sum.
有人知道如何在不损失准确性的情况下通过将这些数字分成一些部分来计算小双数的总和吗?
Does someone know how to calculate the sum of small double numbers by partitioning these numbers into some parts without loosing accuracy?
推荐答案
使用Kahan Summation:
#include <numeric>
#include <iostream>
#include <vector>
struct KahanAccumulation
{
double sum;
double correction;
};
KahanAccumulation KahanSum(KahanAccumulation accumulation, double value)
{
KahanAccumulation result;
double y = value - accumulation.correction;
double t = accumulation.sum + y;
result.correction = (t - accumulation.sum) - y;
result.sum = t;
return result;
}
int main()
{
std::vector<double> numbers = {0.01, 0.001, 0.0001, 0.000001, 0.00000000001};
KahanAccumulation init = {0};
KahanAccumulation result =
std::accumulate(numbers.begin(), numbers.end(), init, KahanSum);
std::cout << "Kahan Sum: " << result.sum << std::endl;
return 0;
}
输出:
Kahan Sum: 0.011101
代码这里.
这篇关于小双数的总和c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:小双数的总和c ++


基础教程推荐
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30