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