小双数之和c ++ [英] sum of small double numbers c++

查看:150
本文介绍了小双数之和c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们在 10 ^( - 15) 2bclass =post-tagtitle =显示问题标记为'c ++'rel =tag> c ++ 。如果我们按顺序计算这个数组中的数字之和,例如

  double sum = 0; 
for(int i = 0; i



我们得到一些值 x p>

但是如果我们将一个数组分成几个部分,然后计算每个部分的和,之后我们将所有的部分和加在一起,我们得到一些值 x2 ,接近 x ,但不完全是 x 。所以我在计算总和时失去了积累。



有人知道如何通过将这些数字分成几个部分而不失准确性来计算小双数的总和?

解决方案

使用 Kahan Summation

  #include< numeric> 
#include< iostream>
#include< vector>

struct KahanAccumulation
{
double sum;
double correction;
};

Kahan积累KahanSum(Kahan积累,双值)
{
Kahan积累结果;
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>数字= {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 

代码此处


Assume that we have an array of small (about 10^(-15) ) double numbers in . 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];

we get some value 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?

解决方案

Using 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;
}

Output:

Kahan Sum: 0.011101

Code here.

这篇关于小双数之和c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆