Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You could use an averaging algorithm where the old values decay linearly. If S_n is the speed at time n and A_{n-1} is the average at time n-1, then define your average speed as follows.</p> <p>A_1 = S_1<br> A_2 = (S_1 + S_2)/2<br> A_n = S_n/(n-1) + A_{n-1}(1-1/(n-1))</p> <p>In English, this means that the longer in the past a measurement occurred, the less it matters because its importance has decayed.</p> <p>Compare this to the normal averaging algorithm: A_n = S_n/n + A_{n-1}(1-1/n)</p> <p>You could also have it geometrically decay, which would weight the most recent speeds very heavily: A_n = S_n/2 + A_{n-1}/2</p> <p>If the speeds are 4,3,5,6 then A_4 = 4.5 (simple average)<br> A_4 = 4.75 (linear decay)<br> A_4 = 5.125 (geometric decay)<br></p> <h2>Example in PHP</h2> <p><strong>Beware that <code>$n+1</code> (not <code>$n</code>) is the number of current data points due to PHP's arrays being zero-indexed. To match the above example set <code>n == $n+1</code> or <code>n-1 == $n</code></strong></p> <pre><code>&lt;?php $s = [4,3,5,6]; // average $a = []; for ($n = 0; $n &lt; 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 &lt; 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 &lt; 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); </code></pre> <p>Output</p> <pre><code>array (size=4) 0 =&gt; int 4 1 =&gt; float 3.5 2 =&gt; float 4 3 =&gt; float 4.5 array (size=4) 0 =&gt; int 4 1 =&gt; float 3.5 2 =&gt; float 4.25 3 =&gt; float 4.8333333333333 array (size=4) 0 =&gt; int 4 1 =&gt; float 3.5 2 =&gt; float 4.25 3 =&gt; float 5.125 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload