问题描述
以下代码的结果让我非常惊讶。为什么使用 accumulate
会产生这么大的错误?我知道因为它是单精度,所以它会有一个舍入误差,但是在没有任何策略(单精度)的情况下使用 reduce 时,这个舍入误差并不那么重要!事实上,舍入误差是合理的。但同样,当我将 reduce
与策略(par seq unseq 中的任一种)一起使用时,与精确总和相比,它的结果将是相同的,但误差如此之大。谁能解释一下?
#include <fstream>
#include <iomanip>
#include <execution>
#include <random>
#include <iostream>
#include <chrono>
#include <cfloat>
using namespace std;
int main() {
const int N=100*1e6;
default_random_engine g(time(0));
uniform_real_distribution<float> d(0.0f,nextafter(1.0f,DBL_MAX));
vector<float> a;
vector<double> b;
double exact{0.0};
float sum;
for(auto i=0; i<N ;i++){
a.push_back(d(g));
b.push_back(static_cast<double>(a[i]));
}
exact=accumulate(b.begin(),b.end(),0.0);
cout<<" exact sum is: "<<exact<<endl;
sum=accumulate(a.begin(),a.end(),0.0f);
cout<<" using accumulate for float : "<<sum<<endl;
sum=reduce(a.begin(),a.end());
cout<<" using reduce for float : "<<sum<<endl;
sum=reduce(execution::unseq,a.begin(),a.end());
cout<<" using reduce with ploicy : "<<sum<<endl;
}
结果是:
exact sum is: 4.99979e+07
using accumulate for float : 1.67772e+07
using reduce for float : 5.00006e+07
using reduce with ploicy : 1.67772e+07
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)