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.
这篇关于计算所有值的总和超过双精度限制的平均值的好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:计算所有值的总和超过双精度限制的平均值的好


- C++ 和 Java 进程之间的共享内存 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01