tag:blogger.com,1999:blog-1265125331765205173.post2775394592155189728..comments2024-03-13T09:09:15.066+01:00Comments on Dreamstate Coding: RunningAverage,how to calculate average without storing each individual value in C#Unknownnoreply@blogger.comBlogger2125tag:blogger.com,1999:blog-1265125331765205173.post-28418607644301650222017-01-03T23:10:34.665+01:002017-01-03T23:10:34.665+01:00Hi there, thank you for pointing this out. Post up...Hi there, thank you for pointing this out. Post updated to reflect this better solution :)Eowindhttps://www.blogger.com/profile/07393994040841014328noreply@blogger.comtag:blogger.com,1999:blog-1265125331765205173.post-70946120278083384352017-01-03T11:25:36.624+01:002017-01-03T11:25:36.624+01:00Not very effective(1) or precise(2):
1) you calcul...Not very effective(1) or precise(2):<br />1) you calculate the sum and average every time you add a number: it would be faster to just increment the count and add to the sum (which should be an instance var instead of a local var)<br />2) you will get rounding errors on numbers with just a few counts: when you keep doing it again and again the lack of precision will be cumulative. It's much more precise to have a method (or property> that yields the average when you need it.<br /><br />Instead:<br />Declare "private float _sum;" instead of the _average var.<br />Make Average a get property.<br />Add a RunningAverage() method that initializes the _count and the _sum. <br />Add a Average() method which returns _sum/_count instead of _average.<br />Change the Add method to just add v to _sum and increment _count.<br /><br />Since you will probably add numbers much more often than you will get the average the Add() method should be as fast as possible. The Average method will be at least as fast as the calculating part of the original Add() method, but the calculation will only be performed when you need it.<br /><br />Greetings<br />/Dan Anonymoushttps://www.blogger.com/profile/02761329099913405523noreply@blogger.com