计算所有值的总和超过双精度限制的平均值的好方法是什么? [英] What is a good solution for calculating an average where the sum of all values exceeds a double's limits?

查看:40
本文介绍了计算所有值的总和超过双精度限制的平均值的好方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要计算一组非常大的双打(10^9 个值)的平均值.值的总和超过了 double 的上限,那么有谁知道计算平均值的任何巧妙的小技巧,而不需要计算总和?

I have a requirement to calculate the average of a very large set of doubles (10^9 values). The sum of the values exceeds the upper bound of a double, so does anyone know any neat little tricks for calculating an average that doesn't require also calculating the sum?

我使用的是 Java 1.5.

I am using Java 1.5.

推荐答案

您可以迭代计算均值.该算法简单、快速,您只需处理每个值一次,并且变量永远不会大于集合中的最大值,因此不会出现溢出.

You can calculate the mean iteratively. This algorithm is simple, fast, you have to process each value just once, and the variables never get larger than the largest value in the set, so you won't get an overflow.

double mean(double[] ary) {
  double avg = 0;
  int t = 1;
  for (double x : ary) {
    avg += (x - avg) / t;
    ++t;
  }
  return avg;
}

在循环内 avg 始终是到目前为止处理的所有值的平均值.换句话说,如果所有值都是有限的,则不应出现溢出.

Inside the loop avg always is the average value of all values processed so far. In other words, if all the values are finite you should not get an overflow.

这篇关于计算所有值的总和超过双精度限制的平均值的好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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