FastRng/FastRngTests/Double/RunningStatistics.cs

47 lines
1.3 KiB
C#
Raw Normal View History

2020-09-26 19:38:34 +00:00
using System;
namespace FastRngTests.Double
{
internal sealed class RunningStatistics
{
private double previousM;
private double previousS;
private double nextM;
private double nextS;
public RunningStatistics()
{
}
public int NumberRecords { get; private set; } = 0;
public void Clear() => this.NumberRecords = 0;
public void Push(double x)
{
this.NumberRecords++;
// See Knuth TAOCP vol 2, 3rd edition, page 232
if (this.NumberRecords == 1)
{
2020-09-29 15:30:07 +00:00
this.previousM = this.nextM = x;
this.previousS = 0.0;
2020-09-26 19:38:34 +00:00
}
else
{
2020-09-29 15:30:07 +00:00
this.nextM = this.previousM + (x - this.previousM) / this.NumberRecords;
this.nextS = this.previousS + (x - this.previousM) * (x - this.nextM);
2020-09-26 19:38:34 +00:00
// set up for next iteration
2020-09-29 15:30:07 +00:00
this.previousM = this.nextM;
this.previousS = this.nextS;
2020-09-26 19:38:34 +00:00
}
}
2020-09-29 15:30:07 +00:00
public double Mean => this.NumberRecords > 0 ? this.nextM : 0.0;
2020-09-26 19:38:34 +00:00
2020-09-29 15:30:07 +00:00
public double Variance => this.NumberRecords > 1 ? this.nextS / (this.NumberRecords - 1) : 0.0;
2020-09-26 19:38:34 +00:00
public double StandardDeviation => Math.Sqrt(this.Variance);
}
}