简体   繁体   English

您如何计算 C# 中给定数据集的移动平均值?

[英]How do you compute for the moving average of a given dataset in C#?

So I use a randomly generated dataset and I need to find the moving average of the sample size the user inputted.所以我使用一个随机生成的数据集,我需要找到用户输入的样本大小的移动平均值。 For example, the dataset is a list with {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} and the sample size the user inputted is 2. The program must calculate first the mean of: 1 and 2 = 1.5, 2 and 3 = 2.5, 3 and 4 = 3.5, and so on.例如,数据集是一个包含 {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} 的列表,用户输入的样本量为 2。程序必须首先计算:1和 2 = 1.5、2 和 3 = 2.5、3 和 4 = 3.5,以此类推。 How do I do this?我该怎么做呢? Thanks!谢谢!

You can keep track of the sum and queue up all the values so you know what to subtract from the sum once you get to the sample size.您可以跟踪总和并将所有值排队,这样您就知道在达到样本大小后要从总和中减去什么。

public static IEnumerable<decimal> MovingAverages(IEnumerable<decimal> values, int sample)
{
    var queue = new Queue<decimal>(sample);
    decimal sum = 0;
    foreach(var x in values)
    {
        sum += x;
        queue.Enqueue(x);
        if(queue.Count == sample)
        {
            yield return sum / sample;
            sum -= queue.Dequeue();
        }
    }
}

Basically this will queue up the first n values (equal to sample) and the sum.基本上这会将前 n 个值(等于样本)和总和排队。 Once it gets the desired number of values to average it yields the sum divided by the sample size and then removes the oldest value from the queue and subtracts it from the sum.一旦获得所需数量的值进行平均,它就会产生总和除以样本大小,然后从队列中删除最旧的值并从总和中减去它。 Note that if the sample size is larger than the number of values this will return an empty enumerable.请注意,如果样本大小大于值的数量,这将返回一个空的可枚举。

This can be done with a simple loop.这可以通过一个简单的循环来完成。

for (int i = 0; i <= array.Length - samplesize; i++)
    Console.WriteLine(array.Skip(i).Take(samplesize).Average());

The Skip(i).Take(samplesize) portion selects only the elements you are interested in at the moment. Skip(i).Take(samplesize)部分仅选择您目前感兴趣的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM