Skip to content

Instantly share code, notes, and snippets.

@rightfold
Last active December 30, 2015 20:08
Show Gist options
  • Save rightfold/7878313 to your computer and use it in GitHub Desktop.
Save rightfold/7878313 to your computer and use it in GitHub Desktop.
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