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 ++
基础教程推荐
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- C++,'if' 表达式中的变量声明 2021-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 设计字符串本地化的最佳方法 2022-01-01