nextDouble
nextDouble

Reputation: 43

Averaging multiple results of a method?

So, I have a method that is looping through and returning these numbers automatically :

6527.6    6755.6    7009.9    7384.7    7775.9    8170.7    8382.6    8598.8    8867.6    9208.2    9531.8    9821.7   10041.6   10007.2    9847.0   10036.3   10263.5   10449.7   10699.7

I would like to average the first number to the second number, the second to the third number, and so on. What ways should I go about doing this? Adding all these doubles to an array? Or is there a way to get a running total in order to do this?

The problem I'm having is that I can only seem to get all or none of these doubles, not specific ones.

So the output would be the results of something like (6527.6+6755.6)/2, (6755.6+7009.9)/2, and so on. Just printing them, nothing else.

Edit : Code from the parser here : http://pastebin.com/V6yvntcP

Upvotes: 0

Views: 70

Answers (2)

Juhi Saxena
Juhi Saxena

Reputation: 1217

Create and array of double and just do some traversing and swapping and its done. Check it out:

  double[] array = { 6527.6, 6755.6, 7009.9, 7384.7, 7775.9, 8170.7 };
        double avg = 0;
        double sum = 0.0;
        double temp = 6527.6;
        for (int i = 0; i < array.length - 1; i++) {
            sum = temp + array[i + 1];
            avg = sum / 2;
            System.out.println("(" + temp + "+" + array[i + 1] + ")/2" + "= "
                    + avg);
            temp = avg;

        }

Upvotes: 0

przemek hertel
przemek hertel

Reputation: 4014

What you are describing is known as moving average. Some formal explanation is here:

http://en.wikipedia.org/wiki/Moving_average

[...] simple moving average (SMA) is the unweighted mean of the previous n data [...]

You want to compute moving average for n = 2.

Below is simple code that do this:

public static void main(String[] args) {
    List<Double> list = Arrays.asList(6527.6, 6755.6, 7009.9, 7384.7, 7775.9, 8170.7);

    for (int i = 1; i < list.size(); i++) {
        double avg = (list.get(i) + list.get(i - 1)) / 2;
        System.out.println("avg(" + (i - 1) + "," + i + ") = " + avg);
    }
}

And second approach without List or array:

Double prev = null;

// inside loop:

double curr = getMethodResult(...);

if (prev != null) {
    double avg = (curr + prev) / 2;
}

prev = curr;

// end of loop

Upvotes: 1

Related Questions