相关疑难解决方法(0)

应该添加浮点数以获得最精确的结果?

这是我在最近的采访中被问到的一个问题,我想知道(我实际上并不记得数值分析的理论,所以请帮助我:)

如果我们有一些累积浮点数的函数:

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

vstd::vector<float>例如,是一个.

  • 在累积它们之前对这些数字进行排序会更好吗?

  • 哪个订单会给出最准确的答案?

我怀疑按升序排序数字实际上会减少数值误差,但不幸的是我无法证明这一点.

PS我确实意识到这可能与现实世界的编程无关,只是好奇.

c++ floating-point precision

105
推荐指数
4
解决办法
1万
查看次数

为什么循环给出不同的结果而不是积累?

我在这里发布了一个实现Kahan求和的答案:https://stackoverflow.com/a/41743731/2642059我用了一个lambda accumulate:

accumulate(next(cbegin(small)), cend(small), big, [c = 0.0](const auto& sum, const auto& input) mutable {
    const auto y = input - c;
    const auto t = sum + y;

    c = t - sum - y;
    return t;
} )
Run Code Online (Sandbox Code Playgroud)

这应该与for-loop 具有相同的结果:

auto sum = big;
auto c = 0.0;

for (long i = 0; i < size(small); ++i) {
    const auto y = small[i] - c;
    const auto t = sum + …
Run Code Online (Sandbox Code Playgroud)

c++ lambda for-loop accumulate

1
推荐指数
1
解决办法
134
查看次数

标签 统计

c++ ×2

accumulate ×1

floating-point ×1

for-loop ×1

lambda ×1

precision ×1