Last active
December 30, 2015 20:08
-
-
Save rightfold/7878313 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static unsafe IEnumerable<double> MovingAverage(IList<double> list, int period) | |
{ | |
double* doubles = stackalloc double[period]; | |
double fraction = 1.0 / period; | |
double sum = 0; | |
for (int i = 0; i < period; i++) | |
{ | |
double @double = list[i] * fraction; | |
doubles[i] = @double; | |
sum += @double; | |
} | |
yield return sum; | |
int j = period; | |
int index = 0; | |
while (j < list.Count) | |
{ | |
double old = doubles[index]; | |
sum -= old; | |
double @new = list[j] * fraction; | |
doubles[index] = @new; | |
sum += @new; | |
yield return sum; | |
j++; | |
index++; | |
if (index == period) | |
index = 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment