title: How to calculate iteratively the running weighted average so that last values to weight most?
body: <p>I want to implement an iterative algorithm, which calculates weighted average. The specific weight law does not matter, but it should be close to 1 for the newest values and close to 0 to the oldest.</p>
  
  <p>The algorithm should be iterative. i.e. it should not remember all previous values. It should know only one newest value and any aggregative information about past, like previous values of the average, sums, counts etc.</p>
  
  <p>Is it possible?</p>
  
  <p>For example, the following algorithm can be:</p>
  
  <pre><code>void iterate(double value) {
     sum *= 0.99;
     sum += value;
     count++;
     avg = sum / count;
  }
  </code></pre>
  
  <p>It will give exponential decreasing weight, which may be not good. Is it possible to have step decreasing weight or something?</p>
  
  <p><strong>EDIT 1</strong></p>
  
  <p>The the requirements for weighing law is follows:</p>
  
  <p>1) The weight decreases into past
  2) I has some mean or characteristic duration so that values older this duration matters much lesser than newer ones
  3) I should be able to set this duration</p>
  
  <p><strong>EDIT 2</strong></p>
  
  <p>I need the following. Suppose <code>v_i</code> are values, where <code>v_1</code> is the first. Also suppose <code>w_i</code> are weights. But <code>w_0</code> is THE LAST.</p>
  
  <p>So, after first value came I have first average</p>
  
  <pre><code> a_1 = v_1 * w_0
  </code></pre>
  
  <p>After the second value v_2 came, I should have average </p>
  
  <pre><code> a_2 = v_1 * w_1 + v_2 * w_0
  </code></pre>
  
  <p>With next value I should have</p>
  
  <pre><code> a_3 = v_1 * w_2 + v_2 * w_1 + v_3 * w_0
  </code></pre>
  
  <p>Note, that weight profile is moving with me, while I am moving along value sequence.</p>
  
  <p>I.e. each value does not have it's own weight all the time. My goal is to have this weight lower while going to past.</p>