我正在尝试用 Java 重写 MATLAB 代码,但遇到了一个奇怪的问题。它只重复第一个值,但它会循环获取 ArrayList 的正确大小。
MATLAB 代码
function m = ema(x,N)
L = length(x);
m = zeros(L,1);
w = 2/(N+1);
m(1) = x(1);
for i=2:L
m(i) = w*(x(i)-m(i-1)) + m(i-1);
end
end
Java代码
public static ArrayList<Double> getEma(ArrayList<Double> x, int frame) {
ArrayList<Double> m = new ArrayList<>();
double w = (2 / (frame + 1));
m.add(x.get(0));
for (int i=1; i < x.size(); i++) {
double value = (w * (x.get(i) - m.get(i-1))) + m.get(i-1);
m.add(value);
}
return m;
}
JUnit 测试结果
Expected :[23.11, 23.32, 23.78, 24.06, 24.29, 24.19, 23.82, 23.53, 23.63, 23.62, 23.41, 23.23, 23.51, 23.79, 24.13, 24.69, 25.05, 25.37, 25.53, 25.56, 25.84, 25.73, 25.88, 25.45, 25.01, 24.8, 24.44, 24.18, 24.58, 25.37]
Actual :[23.11, 23.11, 23.11, 23.11, 23.11, 23.11, 23.11, 23.11, 23.11, 23.11, 23.11, 23.11, 23.11, 23.11, 23.11, 23.11, 23.11, 23.11, 23.11, 23.11, 23.11, 23.11, 23.11, 23.11, 23.11, 23.11, 23.11, 23.11, 23.11, 23.11]
最佳答案
将输入从intframe
更改为doubleframe
或将frame
转换为double
或将2
-> 2.0
和 1
-> 1.0
在计算 w 时自动转换为 double 型而不进行强制转换。
public static ArrayList<Double> getEma(ArrayList<Double> x, int frame) {
ArrayList<Double> m = new ArrayList<Double>();
double w = (2 / ((double) frame + 1));
m.add(x.get(0));
for (int i=1; i < x.size(); i++) {
double value = (w * (x.get(i) - m.get(i-1))) + m.get(i-1);
m.add(value);
}
return m;
}
关于java - For 循环和计算移动平均线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32255717/