(Language PHP - This question is for any language, particularly I'm using PHP) For example you have an array of numbers like:
$q = array( 1, 2, 3, 4, 5, ... ); // ... mean you can give more numbers
$i = 0;
$currentAverage = 0;
while ($i < count( $q )) {
$currentAverage = ($currentAverage + $q[$i]) / 2; // this is my try
$i++;
}
echo "The final average is: " . $currentAverage . "<br/>";
Obviusly, you can divide by count( $q )
the sum, but that's not the idea.
I hope you can help me! thanks.
You can't calculate an "incremental" mean average without knowing the total number of items make up that average.
For example, if you have 10 items that average 5 and you want to add the next item,
X
, you have to give the appropriate "weight" to the newly added item.For example, to get the next average, you would do
If we say
X
is 7, the new average would beIt is impossible to do this calculation without knowing the current number of items that make up the average (10) beforehand
To show you this working in an incremental fashion, here is a
for
loop that keeps track of the average as the loop is running