用ojalgo计算滚动平均值

时间:2018-04-26 14:41:00

标签: ojalgo

使用ojalgo计算滚动均值的最佳方法是什么?

第一个SampleSet正在添加每个数字,与窗口大小相同。

其次,代码意图不明显。

我有:

    final Array1D<Double> doubles = Array1D.factory(Primitive32Array.FACTORY).makeFilled(10, new Uniform());
    System.out.println(doubles.toString());

    final Array1D<Double> rollingMedian = Array1D.PRIMITIVE32.makeZero(doubles.size());

    rollingMedian.set(0, doubles.get(0));
    System.out.printf("%1$s -> %1$s\n", doubles.get(0));

    final Array1D<Double> someSamples2 = doubles.subList(0, 2);
    final double mean2 = SampleSet.wrap(someSamples2).getMean();
    rollingMedian.set(1, mean2);
    System.out.printf("%s -> %s\n", someSamples2.toString(), mean2);

    for (int i = 2; i < doubles.length; i++) {
        final Array1D<Double> someSamples = doubles.subList(i - 2, i + 1);
        final double mean = SampleSet.wrap(someSamples).getMean();
        rollingMedian.set(i, mean);
        System.out.printf("%s -> %s\n", someSamples.toString(), mean2);
    }

    System.out.println(rollingMedian.toString());

哪个不好...

1 个答案:

答案 0 :(得分:1)

不确定哪种方式最好,但这是另一种选择:

    for (int i = 0; i < doubles.length; i++) {
        int first = Math.max(0, i - 2);
        int limit = i + 1;
        double mean = doubles.aggregateRange(first, limit, Aggregator.AVERAGE);
        rollingMedian.set(i, mean);
    }