PageRenderTime 52ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/trunk/SourceCode/Common/CommonSupport/Math/SimpleMovingAverage.cs

#
C# | 73 lines | 49 code | 9 blank | 15 comment | 5 complexity | 10457115a98d2d78dbc977b2268835c8 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception
  1. using System;
  2. namespace CommonSupport
  3. {
  4. public class SimpleMovingAverage : IMovingAverage
  5. {
  6. CircularList<float> samples;
  7. protected float total;
  8. /// <summary>
  9. /// Get the average for the current number of samples.
  10. /// </summary>
  11. public float Average
  12. {
  13. get
  14. {
  15. if (samples.Count == 0)
  16. {
  17. throw new ApplicationException("Number of samples is 0.");
  18. }
  19. return total / samples.Count;
  20. }
  21. }
  22. /// <summary>
  23. /// Constructor, initializing the sample size to the specified number.
  24. /// </summary>
  25. public SimpleMovingAverage(int numSamples)
  26. {
  27. if (numSamples <= 0)
  28. {
  29. throw new ArgumentOutOfRangeException("numSamples can't be negative or 0.");
  30. }
  31. samples = new CircularList<float>(numSamples);
  32. total = 0;
  33. }
  34. /// <summary>
  35. /// Adds a sample to the sample collection.
  36. /// </summary>
  37. public void AddSample(float val)
  38. {
  39. if (samples.Count == samples.Length)
  40. {
  41. total -= samples.Value;
  42. }
  43. samples.Value = val;
  44. total += val;
  45. samples.Next();
  46. }
  47. /// <summary>
  48. /// Clears all samples to 0.
  49. /// </summary>
  50. public void ClearSamples()
  51. {
  52. total = 0;
  53. samples.Clear();
  54. }
  55. /// <summary>
  56. /// Initializes all samples to the specified value.
  57. /// </summary>
  58. public void InitializeSamples(float v)
  59. {
  60. samples.SetAll(v);
  61. total = v * samples.Length;
  62. }
  63. }
  64. }