有没有办法找到算术平均值"好"比之和()/ N [英] Is there any way to find arithmetic mean "better" than sum()/N?

查看:131
本文介绍了有没有办法找到算术平均值"好"比之和()/ N的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有N个数字(整数,浮点数,任何你想要的),并希望找到自己的算术平均值。最简单的方法是通过值的数目来总结所有的价值和鸿沟:

Suppose we have N numbers(integers, floats, whatever you want) and want to find their arithmetic mean. Simplest method is to sum all values and divide by number of values:

def simple_mean(array[N]): # pseudocode
    sum = 0
    for i = 1 to N
       sum += array[i]
    return sum / N

它工作正常,但需要大整数。 如果我们不希望大整数和我们都是精品与舍入误差,N是2的幂,我们可以使用分而治之:((A + B)/ 2 + (C + D)/ 2)/ 2 =(A + B + C + D)/ 4 ((A + B + C + D)/ 4 +( E + F + G + H)/ 4)/ 2 =(A + B + C + D + E + F + G + H)/ 8 ,等等。

It works fine, but requires big integers. If we don't want big integers and we are fine with rounding errors, and N is the power of two, we can use 'divide-and-conquer' : ((a+b)/2 + (c+d)/2)/2 = (a+b+c+d)/4, ((a+b+c+d)/4 + (e+f+g+h)/4)/2 = (a+b+c+d+e+f+g+h)/8, so on.

def bisection_average(array[N]):
   if N == 1: return array[1]
   return (bisection_average(array[:N/2])+bisection_average(array[N/2:]))/2

其他方法吗?

Any other ways?

PS。 操场懒惰

推荐答案

克努特列出了下面的方法来计算给定浮点(原上页中的计算机编程的艺术第2卷,1998年版;我下面的适应避免特殊套管第一次迭代):

Knuth lists the following method for calculating mean and standard deviation given floating point (original on p. 232 of Vol 2 of The Art of Computer Programming, 1998 edition; my adaptation below avoids special-casing the first iteration):

double M=0, S=0;

for (int i = 0; i < N; ++i)
{
    double Mprev = M;
    M += (x[i] - M)/(i+1);
    S += (x[i] - M)*(x[i] - Mprev);
}

// mean = M
// std dev = sqrt(S/N) or sqrt(S/N+1)
// depending on whether you want population or sample std dev

这篇关于有没有办法找到算术平均值&QUOT;好&QUOT;比之和()/ N的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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