Able
Askowl Base Library Enabler
ExponentialMovingAverage.cs
1 // Copyright 2018 (C) paul@marrington.net http://www.askowl.net/unity-packages
2 
3 using UnityEngine;
4 
5 namespace Askowl {
6  /// <a href="http://bit.ly/2NTA3Ed">An **exponential moving average** is a way to calculate an average where older values have less impact on the average than more recent ones.</a>
7  public class ExponentialMovingAverage {
8  private readonly float alpha;
9  private float average = float.NaN;
10 
11  /// <a href="http://bit.ly/2OpRz2k">Initialise with a look-back parameter - being how many points will effect the current value.</a>
12  public ExponentialMovingAverage(int lookBack = 9) => alpha = 2.0f / (lookBack + 1);
13 
14  /// <a href="http://bit.ly/2Rj0UHY">Method with side-effects. Provide the next sample in the stream and get give back the exponential moving average.</a>
15  public float Average(float value) => average = float.IsNaN(average) ? value : ((value - average) * alpha) + average;
16 
17  /// <a href="http://bit.ly/2OxNV6I">Method with side-effects. Provide the next sample in the stream of angles and get give back the exponential moving average in degrees. Result will be between -180 and 180.</a>
18  public float AverageAngle(float degrees) {
19  float difference = Mathf.Repeat(degrees - average, 360);
20  if (difference > 180) difference -= 360;
21  return average = float.IsNaN(average) ? degrees : (difference * alpha) + average;
22  }
23  }
24 }
Definition: Clock.cs:3
An exponential moving average is a way to calculate an average where older values have less impact on...
ExponentialMovingAverage(int lookBack=9)
Initialise with a look-back parameter - being how many points will effect the current value...
float Average(float value)
Method with side-effects. Provide the next sample in the stream and get give back the exponential mov...
float AverageAngle(float degrees)
Method with side-effects. Provide the next sample in the stream of angles and get give back the expon...