Mirror Networking
ExponentialMovingAverage.cs
1// N-day EMA implementation from Mirror with a few changes (struct etc.)
2// it calculates an exponential moving average roughly equivalent to the last n observations
3// https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
4using System;
5
6namespace Mirror
7{
9 {
10 readonly float alpha;
11 bool initialized;
12
13 public double Value;
14 public double Variance;
15 [Obsolete("Var was renamed to Variance")] // 2022-06-17
16 public double Var => Variance;
17 public double StandardDeviation; // absolute value, see test
18
19 public ExponentialMovingAverage(int n)
20 {
21 // standard N-day EMA alpha calculation
22 alpha = 2.0f / (n + 1);
23 initialized = false;
24 Value = 0;
25 Variance = 0;
26 StandardDeviation = 0;
27 }
28
29 public void Add(double newValue)
30 {
31 // simple algorithm for EMA described here:
32 // https://en.wikipedia.org/wiki/Moving_average#Exponentially_weighted_moving_variance_and_standard_deviation
33 if (initialized)
34 {
35 double delta = newValue - Value;
36 Value += alpha * delta;
37 Variance = (1 - alpha) * (Variance + alpha * delta * delta);
38 StandardDeviation = Math.Sqrt(Variance);
39 }
40 else
41 {
42 Value = newValue;
43 initialized = true;
44 }
45 }
46 }
47}