You can use the averaging algorithm, where old values will decrease linearly. If S_n is the speed at time n, and A_ {n-1} is the average value of time n-1, then determine your average speed as follows.
A_1 = S_1
A_2 = (S_1 + S_2) / 2
A_n = S_n / (n-1) + A_ {n-1} (1-1 / (n-1))
In English, this means that the longer a measurement has taken place in the past, the less it matters because its value has died out.
Compare this with the usual averaging algorithm: A_n = S_n / n + A_ {n-1} (1-1 / n)
You could also have its geometrically decay, which would greatly affect the latest speeds: A_n = S_n / 2 + A_ {n-1} / 2
If the speed is 4.3.5.6, then A_4 = 4.5 (simple average value)
A_4 = 4.75 (linear decay)
A_4 = 5.125 (geometric decay)
PHP example
Beware that $n+1 (not $n ) is the number of current data points due to the fact that PHP arrays did not have a zero index. To match the above example, set n == $n+1 or n-1 == $n
<?php $s = [4,3,5,6]; // average $a = []; for ($n = 0; $n < count($s); ++$n) { if ($n == 0) $a[$n] = $s[$n]; else { // $n+1 = number of data points so far $weight = 1/($n+1); $a[$n] = $s[$n] * $weight + $a[$n-1] * (1 - $weight); } } var_dump($a); // linear decay $a = []; for ($n = 0; $n < count($s); ++$n) { if ($n == 0) $a[$n] = $s[$n]; elseif ($n == 1) $a[$n] = ($s[$n] + $s[$n-1]) / 2; else { // $n = number of data points so far - 1 $weight = 1/($n); $a[$n] = $s[$n] * $weight + $a[$n-1] * (1 - $weight); } } var_dump($a); // geometric decay $a = []; for ($n = 0; $n < count($s); ++$n) { if ($n == 0) $a[$n] = $s[$n]; else { $weight = 1/2; $a[$n] = $s[$n] * $weight + $a[$n-1] * (1 - $weight); } } var_dump($a);
Exit
array (size=4) 0 => int 4 1 => float 3.5 2 => float 4 3 => float 4.5 array (size=4) 0 => int 4 1 => float 3.5 2 => float 4.25 3 => float 4.8333333333333 array (size=4) 0 => int 4 1 => float 3.5 2 => float 4.25 3 => float 5.125
Drew Hoskins Apr 28 '09 at 17:37 2009-04-28 17:37
source share