FastRng/FastRngTests/RunningStatistics.cs

44 lines
1.2 KiB
C#
Raw Permalink Normal View History

2020-11-01 09:52:42 +00:00
using System;
2020-11-07 21:43:03 +00:00
using System.Diagnostics.CodeAnalysis;
2020-11-01 09:52:42 +00:00
namespace FastRngTests;
[ExcludeFromCodeCoverage]
internal sealed class RunningStatistics
2020-11-01 09:52:42 +00:00
{
private float previousM;
private float previousS;
private float nextM;
private float nextS;
private int NumberRecords { get; set; } = 0;
public void Clear() => this.NumberRecords = 0;
public void Push(float x)
2020-11-01 09:52:42 +00:00
{
this.NumberRecords++;
// See Knuth TAOCP vol 2, 3rd edition, page 232
if (this.NumberRecords == 1)
2020-11-01 09:52:42 +00:00
{
this.previousM = this.nextM = x;
this.previousS = 0.0f;
2020-11-01 09:52:42 +00:00
}
else
2020-11-01 09:52:42 +00:00
{
this.nextM = this.previousM + (x - this.previousM) / this.NumberRecords;
this.nextS = this.previousS + (x - this.previousM) * (x - this.nextM);
2020-11-01 09:52:42 +00:00
// set up for next iteration
this.previousM = this.nextM;
this.previousS = this.nextS;
2020-11-01 09:52:42 +00:00
}
}
2020-11-01 09:52:42 +00:00
public float Mean => this.NumberRecords > 0 ? this.nextM : 0.0f;
2020-11-01 09:52:42 +00:00
public float Variance => this.NumberRecords > 1 ? this.nextS / (this.NumberRecords - 1f) : 0.0f;
2020-11-01 09:52:42 +00:00
public float StandardDeviation => MathF.Sqrt(this.Variance);
2020-11-01 09:52:42 +00:00
}