tags:

views:

414

answers:

6

Time to test your math skills...

I'm using php to find the average of $num1, $num2, $num3 and so on; upto an unset amount of numbers. It then saves that average to a database.

Next time the php script is called a new number is added to the mix.

Is there a math (most likely algebra) equation that I can use to find the average of the original numbers with the new number included. Or do I need to save the original numbers in the database so I can query them and re-calculate the entire bunch of numbers together?

+1  A: 

If what you mean by average is mean and you don't want to store all numbers then store the amount of numbers:

$last_average = 100;
$total_numbers = 10;
$new_number = 54;

$new_average = (($last_average * $total_numbers) + $new_number) / ($total_number + 1);
slebetman
`$total_numbers` may not be available.
Alix Axel
$total_numbers is a **required** implementation detail for the specified problem. Either implement it or the problem is unsolvable.
slebetman
This will lead to an ever-increasing loss of accuracy. Use $last_total instead of $last_average. See Mike's answer.
GZipp
Ah, true, didn't think about that. It's best to keep the $last_sum as well then.
slebetman
A: 

You need to save all the original numbers in the database.

Alix Axel
A: 

If you know the amount of numbers you can calculate the old sum, add the new one and divide by the old amount plus one.

$oldsum = $average * $amount;
$newaverage = ($oldsum + $newnum) / ($amount + 1);
johannes
@slebetman - But that's the same as the answer you've accepted.
GZipp
Ah.. sorry, I misread the code. I retract my previous comment.
slebetman
+5  A: 
Average = Sum / Number of values

Just store all 3 values, there's no need for anything complicated.

If you store the Average and Sum then calculate Number of values you'll lose a little accuracy due to truncation of Average.

If you store the Average and Number of values then calculate Sum you'll lose even more accuracy. You have more margin for error in calculating a correct value for Number of values than Sum thanks to it being an integer.

Mike
You don't need to store the average, you can compute it without any loss of precision.
starblue
A: 

Typically what you might do is save two pieces of information:

  • the sum of all the numbers
  • the count of numbers

Whenever you want to get the average, divide the sum by the count (taking care for the case of count == 0, of course). Whenever you want to include a new number, add the new number to the sum and increment the count by 1.

Greg Hewgill
A: 

This is called a 'running average' or 'moving average'.

If the database stores the average and the number of values averaged, it will be possible to calculate a new running average for each new value.

pavium