Search code examples
c#weighted-average

Trying to calculate weighted moving average but getting zero as result always


I am trying to get out the "Weighted moving average" of a array of double values.

I have tried to get all peaces from some internet examples together but i always getting zero as result.

Problem is the calulation of "weight", its being zero but it should not be zero, example 1 / 107 = 0,0093457943925234 but the weight double values getting zero, i have tried change to long and decimal and getting the same problem.

Any ideas?

    public static double WeighteedMovingAverage(double[] data)
    {
        double aggregate = 0;
        double weight;
        int item = 1;

        int count = data.Count();

        foreach (var d in data)
        {
            weight = item / count;
            aggregate += d * weight;
            count++;
        }

        return (double)(aggregate / count);
    }

Solution

  • weight = (double)item / (double)count;
    

    need to be double to avoid casting before operation