What is a good solution for calculating an average where the sum of all values exceeds a double#39;s limits?(计算所有值的总和超过双精度限制的平均值的好方法是什么?)
问题描述
我需要计算一组非常大的双打(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.
这篇关于计算所有值的总和超过双精度限制的平均值的好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:计算所有值的总和超过双精度限制的平均值的好


基础教程推荐
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01