Friday, March 19, 2010

Smart Way To Calculate Average

As the Heading suggests, I'm going to give you a smart way to calculate the Average of a given Number series.
(though this method is not new but here you could find: how to use the best way of avg. calculation which in-turn will help you in tunning your code).

Requirement: For average calculation of a number series, how to use the best way, so to save the processing time with better efficiency.

Let us take some numbers for which we have to calculate the average: 5, 6, 8,5,10,12,9,4...

Now Let's calculate the avg. with traditional style(basic rule), if we have to calculate the avg. at:
n=1, avg.=5
n=2, avg.=(6+5)/2=5.5
n=3, avg.=(6+5+8)/3=6.33
n=4, avg.=(6+5+8+4)/4=5.75
n=5,...and so on
If you have to process huge numbers and you need to have the average calculated at each number stage (think about a practical example, the task is to display a graph with current value along with the average value, so in this case you need to have avg. calculated at every level).
If you have huge number to process, believe me this is not going to be a good practice of calculating avg.

Now, calculate the avg. as below:
n=1, avg.=5
n=2, avg.= ((6-5)/2)+5=.5+5=5.5
n=3, avg=((8-5.5)/3)+5.5=6.33
n=4, avg=((4-6.33)/4)+6.33=5.75
......

So, in General: if the average at stage: n-1=p (Here n is the total count of numbers of the given series at that moment)
then average at n(if number is N), avg.=((N-p)/n))+p
I hope this will help you in tunning the code and will increase the response time as processor will enjoy the calculation(as we are eliminating the repeated summation of numbers) in this way rather sum up n numbers every time then divide by n...

Enjoy the Mathematics....