I\'ve designed a function to compute the mean of a list. Although it works fine, but I think it may not be the best solution due to it takes two functions rather than one. Is it
While I am not sure whether or not it would be 'best' to write it in one function, it can be done as follows:
If you know the length (lets call it 'n' here) in advance its easy - you can calculate how much each value 'adds' to the average; that is going to be value/length. Since avg(x1, x2, x3) = sum(x1, x2, x3)/length = (x1 + x2 + x3)/3 = x1/3 + x2/3 + x2/3
If you don't know the length in advance, its a little trickier:
lets say we use the list {x1,x2,x3}
without knowing its n=3.
first iteration would just be x1 (since we assume its only n=1)
second iteration would add x2/2
and divide the existing average by 2 so now we have x1/2 + x2/2
after the third iteration we have n=3 and we would want to have x1/3 +x2/3 + x3/3
but we have x1/2 + x2/2
so we would need to multiply by (n-1)
and divide by n
to get x1/3 + x2/3
and to that we just add the current value (x3) divided by n to end up with x1/3 + x2/3 + x3/3
Generally:
given an average (arithmetic mean - avg) for n-1 items, if you want to add one item(newval) to the average your equation will be:
avg*(n-1)/n + newval/n
. The equation can be proven mathematically using induction.
Hope this helps.
*note this solution is less efficient than simply summing the variables and dividing by the total length as you do in your example.