title: weighted mean with integers
body: <p>The situation: we have an integer based microcontroller and we need to calculate weighted mean (for example, weight 32, like 31-1), and store it in an array.</p>
  
  <p>The the final code will be in C.</p>
  
  <p>(And just to be sure, this is not a homework :) )</p>
  
  <p>We were thinking to store the result of modulus division with the weight on the result (the avg calc) and use it in the next round as additional data.</p>
  
  <p>If we had float, it would be like this:</p>
  
  <pre><code>avg[i] = ( avg[i-1] * (WEIGHT-1) + measured ) / WEIGHT;
  </code></pre>
  
  <p>Since we don't, I was thinking this:</p>
  
  <pre><code>pt = (mod == 0) ? WEIGHT-1 : WEIGHT-2;
  tmp = avg[i-1] * pt + mod + measured;
  avg[i] = tmp / WEIGHT;
  mod = tmp % WEIGHT;
  </code></pre>
  
  <p>But this seem to give me false results, and I'm really stuck with the implementation.</p>
  
  <p>Anyone, with some ideas?</p>
  
  <hr>
  
  <h2>EDIT</h2>
  
  <p>Thank you very much for the fast responses, although I may have not asked the question clear enough: we have a factor of the needed weight from the previous average and the current sample.</p>