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;
}
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…