Standard deviation JAVA

0

Here are my methods for calculating the standard deviation, which for some reason unknown to me does not work (I left my test method here too).

public strictfp Double getMedia(List<Double> valor) {
    try {
        return getSoma(valor) / valor.size();
    } catch (NullPointerException e) {
        throw new IllegalArgumentException("The list has null values");
    }
}

public strictfp Double getSoma(List<Double> valor) {
    Double soma = 0D;
    for (int i = 0; i < valor.size(); i++) {
        soma += valor.get(i);
    }
    return soma;
}

public strictfp Double getDesvioPadrao(List<Double> valor) {
    Double media = getMedia(valor);
    int tam = valor.size();
    Double desvPadrao = 0D;
    for (Double vlr : valor) {
        Double aux = vlr - media;
        desvPadrao += aux * aux;
    }
    return Math.sqrt(desvPadrao / tam);
}
#

Test Method:

@SuppressWarnings("deprecation")
@Test
private void TesteDesvioPadrao() {
    List<Double> valor = new ArrayList<Double>();
    valor.add(13.0);
    valor.add(23.0);
    valor.add(4.0);
    valor.add(2.0);
    valor.add(11.0);
    valor.add(12.0);

    assertEquals(new Double(7.467708), ilbt.getDesvioPadrao(valor));

}
    
asked by anonymous 07.02.2018 / 18:30

1 answer

1

The error is in the standard deviation calculation at the end of the getDesvioPadrao method.

In it you return the square root of the division of variance by the size of the collection. Since you are calculating the standard deviation of a sample , it should be the subtract 1 collection size.

public strictfp Double getDesvioPadrao(List<Double> valor) {
    Double media = getMedia(valor);
    int tam = valor.size();
    Double desvPadrao = 0D;
    for (Double vlr : valor) {
        Double aux = vlr - media;
        desvPadrao += aux * aux;
    }
    return Math.sqrt(desvPadrao / (tam - 1));
}

See working at repl.it     

07.02.2018 / 18:49