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
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?