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


基础教程推荐
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 从 python 访问 JVM 2022-01-01
- Java Swing计时器未清除 2022-01-01