Problem with weighted average logic

Asked

Viewed 72 times

0

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

Add up all the values that have the same weight, then multiply this sum by the said weight. This is done for all different values and weights. Then these results are added up and divided by the total of added weights.

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

I think I’ve made the right logic, I’ve rewritten it in a lot of different ways, but always the same mistake. I decided to divide the result by 2 before printing, but I wanted to understand why my someone is 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 decided as follows:

System.out.println("\nMédia Ponderada equivale a: " + df.format(((soma_1 + soma_2) / (peso_1 + peso_2))/2));
  • Simplest (imho), add the weights , multiply all the pairs weight x values and accumulate a total , divide this total by the sum of the weights

1 answer

1


The logic is partially correct.

I frankly prefer to multiply all the weights already in decimal places.

The error in logic is here:

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

It is necessary to divide by the total weights applied, not only the groups. Média Ponderada

In case, it would look something like:

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

In this case, the z.size()/2 is highlighted for both terms, and the total of the added weights is multiplied.

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

Be very careful with these code patches, they don’t usually work.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.