Math average with php

人盡茶涼 提交于 2019-11-30 08:44:17

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);
array_sum($values) / count($values)
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.

<?php
function avrg()
{
 $count = func_num_args();
 $args = func_get_args();
 return (array_sum($args) / $count);
}
?>

http://php.net/manual/en/function.array-sum.php#101727

Thought that I should share my function

function avg($sum=0,$count=0){
    return ($count)? $sum / $count: NAN;
}
var_dump( avg(array_sum($values),count($values)) );

Will return the average and also take into account 0, for example dividing by zero always returns NaN (Not a number)

1/0 = NaN
0/0 = NaN

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);

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.

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.

function avgvals($avg_vals,$avg_delimiter=',') { 
 if ( (is_string($avg_vals) && strlen($avg_vals) > 2) && (is_string($avg_delimiter) && !empty($avg_delimiter)) ) { 
    $average_vals = explode($avg_delimiter, $avg_vals); 
        $return_vals = ( array_sum($average_vals) / count($average_vals) ); 
 } elseif ( (is_string($avg_vals) && strlen($avg_vals) <= 2) && (is_string($avg_delimiter) && !empty($avg_delimiter)) ) { 
        $return_vals = $avg_vals; 
 } else { 
        $return_vals = FALSE; 
 } 
   return $return_vals; 
}

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!