1

What is best way to compute rolling mean using ojalgo?

First SampleSet is adding every number as many times as windows size is.

Second the code intent is not evident.

I have:

    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());

Which is not nicest...

user482745
  • 1,165
  • 1
  • 11
  • 31

1 Answers1

1

Not sure which would be the nicest way, but here's one alternatives:

    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);
    }
apete
  • 1,250
  • 1
  • 10
  • 16