forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
WelfordsVariance.cs
65 lines (51 loc) · 1.42 KB
/
WelfordsVariance.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
namespace Algorithms.Other;
/// <summary>Implementation of Welford's variance algorithm.
/// </summary>
public class WelfordsVariance
{
/// <summary>
/// Mean accumulates the mean of the entire dataset,
/// m2 aggregates the squared distance from the mean,
/// count aggregates the number of samples seen so far.
/// </summary>
private int count;
public double Count => count;
private double mean;
public double Mean => count > 1 ? mean : double.NaN;
private double m2;
public double Variance => count > 1 ? m2 / count : double.NaN;
public double SampleVariance => count > 1 ? m2 / (count - 1) : double.NaN;
public WelfordsVariance()
{
count = 0;
mean = 0;
}
public WelfordsVariance(double[] values)
{
count = 0;
mean = 0;
AddRange(values);
}
public void AddValue(double newValue)
{
count++;
AddValueToDataset(newValue);
}
public void AddRange(double[] values)
{
var length = values.Length;
for (var i = 1; i <= length; i++)
{
count++;
AddValueToDataset(values[i - 1]);
}
}
private void AddValueToDataset(double newValue)
{
var delta1 = newValue - mean;
var newMean = mean + delta1 / count;
var delta2 = newValue - newMean;
m2 += delta1 * delta2;
mean = newMean;
}
}