Problem with weighted average logic

0

According to all the sources I consulted, several to be sure, the weighted average is calculated as follows:

Add all values that have the same weight, then multiply that sum by that weight. This is done for all different values and weights. Then add these results and divide by the total of weights added.

Well, I created an algorithm in java that calculates the weighted average in this way, but the result was always twice that expected. If it should be 3.8, it would generate 7.6, if it was 4.1 it would return 8.2. I can not find where I am by multiplying by 2 to get this doubling result.

I believe that I have done the correct logic, I have rewritten in several different ways, but always the same error. I decided to split the result by 2 before starting, but I wanted to understand why I was doing this.

public void mediaPonderada(int x) {
    ArrayList<Double> z = new ArrayList(gera(x));
    double peso_1 = 0;
    double peso_2 = 0;
    double soma_1 = 0;
    double soma_2 = 0;

    System.out.printf("Informe o peso do primeiro grupo de valores: ");
    peso_1 = ler.nextDouble();
    System.out.printf("Informe o peso do segundo grupo de valores: ");
    peso_2 = ler.nextDouble();

    System.out.println("\nValores: ");
    System.out.println("Grupo 1: \n");
    for (int i = 0; i < (z.size() / 2); i++) {
        System.out.println(df.format(z.get(i)));
        soma_1 += z.get(i);
    }
    soma_1 *= peso_1;

    System.out.println("\nGrupo 2: \n");
    for (int i = (z.size() / 2); i < (z.size()); i++) {
        System.out.println(df.format(z.get(i)));
        soma_2 += z.get(i);
    }
    soma_2 *= peso_2;
    System.out.println("\nMédia Ponderada equivale a: " + df.format(((soma_1 + soma_2) / (peso_1 + peso_2))));
}

I solved it as follows:

System.out.println("\nMédia Ponderada equivale a: " + df.format(((soma_1 + soma_2) / (peso_1 + peso_2))/2));
    
asked by anonymous 18.03.2018 / 21:41

1 answer

1

The logic is partially correct.

I frankly prefer to multiply all the weights already in decimals.

The error in logic is here:

df.format(((soma_1 + soma_2) / (peso_1 + peso_2)))

It is absolutely necessary to divide by the total of applied weights, not only the groups.

In this case, it would look something like this:

 df.format(((soma_1 + soma_2) / ((peso_1 + peso_2)*z.size()/2)))

In this case, put the z.size () / 2 in evidence for both terms, and multiply the total of the weights added.

PS: Your split-by-two solution only works on a 4-element ArrayList, for 6, you would have to divide by 3, and so on.

Be very careful with these code patches, they do not usually work.

    
18.03.2018 / 22:57