使用 std::accumulate 以最佳精度添加浮点数

san*_*san 2 c++ stl

我想将总数累加为双精度而不是浮点数。

vector<float> v;
....
double total  = std::accumulate(v.begin(),
                                v.end(),
                                static_cast<double>(0.0));
//This compiles but I am not sure it is doing what I want
Run Code Online (Sandbox Code Playgroud)

...

double total_ = std::accumulate<double>(v.begin(),
                                        v.end(),
                                        static_cast<double>(0.0)
                                       );

// This doesnt compile, which leads me to believe the first accumulate
// is coercing the double(0.0) back to float.
Run Code Online (Sandbox Code Playgroud)

有没有一种STL惯用且简洁的写法

double total = 0.0;
for (int i = 0; i < v.size(); ++i) {
  total += v[i];
}
Run Code Online (Sandbox Code Playgroud)

仅使用标准库。

我知道这不足以保持精度。

jua*_*nza 8

中使用的累加类型std::accumulate是从第三个参数的类型推导出来的。文字0.0是 a double,因此这使用 执行累积double,而不需要显式转换:

double total  = std::accumulate(v.begin(), v.end(), 0.0);
Run Code Online (Sandbox Code Playgroud)

它相当于

double sum = 0.0;
for (f : v) sum += f;
Run Code Online (Sandbox Code Playgroud)