Trying to calculate weighted moving average but getting zero as result always
-
20-12-2019 - |
Question
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
OTHER TIPS
public static double WeighteedMovingAverage(double[] data)
{
double aggregate = 0;
double weight;
int item = 1;
int count = data.Count();
foreach (var d in data)
{
//replace with line below weight = item / count;
weight = (double)item / (double)count;
aggregate += d * weight;
count++;
}
//replace with line below return (double)(aggregate / count);
return (double)(aggregate / (double)count);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow