Search code examples
phpmathaverage

Math average with php


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?


Solution

  • If what you mean by average is the 'mean' and you don't want to store all numbers then store their count:

    $last_average = 100;
    $total_numbers = 10;
    $new_number = 54;
    
    $new_average = (($last_average * $total_numbers) + $new_number) / ($total_numbers + 1);