- Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathWelfordsVariance.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
namespaceAlgorithms.Other;
/// <summary>Implementation of Welford's variance algorithm.
/// </summary>
publicclassWelfordsVariance
{
/// <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>
privateintcount;
publicdoubleCount=>count;
privatedoublemean;
publicdoubleMean=>count>1?mean:double.NaN;
privatedoublem2;
publicdoubleVariance=>count>1?m2/count:double.NaN;
publicdoubleSampleVariance=>count>1?m2/(count-1):double.NaN;
publicWelfordsVariance()
{
count=0;
mean=0;
}
publicWelfordsVariance(double[]values)
{
count=0;
mean=0;
AddRange(values);
}
publicvoidAddValue(doublenewValue)
{
count++;
AddValueToDataset(newValue);
}
publicvoidAddRange(double[]values)
{
varlength=values.Length;
for(vari=1;i<=length;i++)
{
count++;
AddValueToDataset(values[i-1]);
}
}
privatevoidAddValueToDataset(doublenewValue)
{
vardelta1=newValue-mean;
varnewMean=mean+delta1/count;
vardelta2=newValue-newMean;
m2+=delta1*delta2;
mean=newMean;
}
}