如何计算两倍的平均值,以使总误差最小? [英] How to compute the average of doubles, so that the total error is minimal?

查看:62
本文介绍了如何计算两倍的平均值,以使总误差最小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个很长的双打数组,例如 N == 1000000 .

Assume we have a long array of doubles, say, N == 1000000.

array<double, N> arr;

有两种幼稚的方法来计算平均值.首先

There are two naive approaches to compute the average. First

double result = 0;
for (double x : arr) {
    result += x;
}
result /= arr.size();

当值的总和很大时,这可能是不准确的.浮点数就会失去精度.

This may be inaccurate when the sum of values is very big. Floating point numbers lose precision then.

另一种方法是:

double result = 0;
for (double x : arr) {
    result += x / arr.size();
}

当数字较小时,这可能会失去精度.

This may lose precision when the numbers are small.

是否有任何故障安全方法来计算浮点数的简单平均值?赞赏仅使用标准库的解决方案.

Is there any fail-safe way to calculate a simple average of floating point numbers? Solutions, which use only the standard library are appreciated.

推荐答案

如果您希望将精度提高至双精度,则可以使用 Kahan求和,最后除以元素数量.但是,我不知道Kahan求和的标准库实现.

If you want to squeeze more accuracy out of doubles, you can use Kahan summation and finally division by number of elements. There is however no standard library implementation of Kahan summation I know of.

一种简单,标准的方法(几乎与作弊类似)将使用长双精度进行计算,基本上是使用您的第一个实现,并且仅将结果转换回双精度.

An easy, standard way (almost like cheating) would of course be calculation using long doubles, basically using your first implementation and only converting the result back to double precision.

这篇关于如何计算两倍的平均值,以使总误差最小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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