-
Notifications
You must be signed in to change notification settings - Fork 32
/
TimedMovingAverage.cs
66 lines (58 loc) · 1.69 KB
/
TimedMovingAverage.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
66
using System;
using System.Collections.Generic;
namespace Kethane.PartModules
{
internal class TimedMovingAverage
{
private struct TimedValue
{
public readonly float Time;
public readonly float Value;
public TimedValue(float time, float value)
{
Time = time;
Value = value;
}
}
private readonly Queue<TimedValue> values = new Queue<TimedValue>();
private readonly float interval;
public TimedMovingAverage(float interval, float initialValue = 0)
{
this.interval = interval;
values.Enqueue(new TimedValue(interval, initialValue));
}
public void Update(float time, float value)
{
values.Enqueue(new TimedValue(time, value));
}
public float Average
{
get
{
var time = 0f;
var value = 0f;
var removing = values.Count;
foreach (var entry in values)
{
removing--;
if (time + entry.Time > interval)
{
value += entry.Value * (interval - time);
break;
}
else
{
time += entry.Time;
value += entry.Value * entry.Time;
}
}
while (removing > 0)
{
removing--;
values.Dequeue();
}
return value / interval;
}
}
}
}