我试图用这个代码来计算12个月的移动平均线。我有第三列以下的数据是我想要计算平均值的值。
这段代码的问题在于它输出移动平均值作为转换为double的值
//a is an object of the larger class
//x is the collection of values to be averaged
public int bars = 1;
double[] movavg = new double[x.length - bars]; //
int k = 0;
try {
for (int i = a.bars - 1; i < a.x.length - 1; i++) // for each bar
{
a.movavg[a.k] = 0.0;
for (int j = 0; j < a.bars; j++) // sum over 'bars' previous input values
{
a.movavg[a.k] += a.x[i - j];
}
double k = a.movavg[a.k++] /= a.bars; // divide by number of bars
System.out.println(i + " " + k + " " + a.avgNumerator[i]);
}
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
}
year month value_for_moving_average
2011 1 21333333
2011 2 13500000
2011 3 17285714
2011 4 15500000
2011 5 15800000
2011 6 15900000
2011 7 15875000
2011 8 15600000
2011 9 17666666
2011 10 20000000
2011 11 15958333
2011 12 21583333
2012 1 21519230
2012 2 25450000
2012 3 21400000
2012 4 34166666
2012 5 27928571
2012 6 29250000
2012 7 17550000
2012 8 19111111
2012 9 18200000
2012 10 15181818
2012 11 14455555
2012 12 16900000
2013 1 13500000
2013 2 13600000
2013 3 12812500
结果应该是这个
moving_average
15,868,750
16,446,875
17,228,571
17,098,113
17,056,140
17,512,727
15,891,379
16,056,923
16,188,571
16,515,385
16,270,833
16,671,053
17,241,279
18,296,196
18,547,222
19,431,548
20,334,302
21,014,706
21,089,080
21,520,349
21,408,333
20,737,500
20,745,876
20,493,229
19,597,849
18,323,656
17,704,167
但输出结果是这个
2.1333333E7
1.35E7
1.7285714E7
1.55E7
1.58E7
1.59E7
1.5875E7
1.56E7
1.7666666E7
2.0E7
1.5958333E7
2.1583333E7
2.151923E7
2.545E7
2.14E7
3.4166666E7
2.7928571E7
2.925E7
1.755E7
1.9111111E7
1.82E7
1.5181818E7
1.4455555E7
1.69E7
1.35E7
1.36E7
它的代码输出相同的值,但转换为double
答案 0 :(得分:0)
此代码的问题在于它输出移动平均值作为转换为double的值
这是可以预料的,因为你将平均值计算为双精度数。如果您只想将双重平均值转换为整数,请使用Math.round(double)
; e.g。
System.out.println(i + " " + k + " " +
Math.round(a.avgNumerator[i]));