用于循环和计算移动平均线

时间:2015-08-27 17:21:16

标签: java matlab for-loop

我试图用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]

1 个答案:

答案 0 :(得分:1)

将输入从int frame更改为double frame或将frame转换为double或转为2 - &gt; 2.01 - &gt; 1.0在计算w时自动转换为双精度而无需强制转换。

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;
}