Skip to content

Instantly share code, notes, and snippets.

@ayapi
Created November 27, 2013 18:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ayapi/7681028 to your computer and use it in GitHub Desktop.
Save ayapi/7681028 to your computer and use it in GitHub Desktop.
不偏標準偏差と母標準偏差をApacheCommonsMathのStatで算出する
import org.apache.commons.math3.stat.descriptive.SynchronizedSummaryStatistics;
import org.apache.commons.math3.util.FastMath;
import org.apache.commons.math3.util.Precision;
import java.util.List;
public class Calculator {
protected Double calculateStandardDiviation(List<Double> scores){
SynchronizedSummaryStatistics stats = new SynchronizedSummaryStatistics();
for (Double score : scores){
stats.addValue(score);
}
Double stdev = stats.getStandardDeviation();
return Precision.round(stdev, 2);
}
protected Double calculatePopulationStandardDiviation(List<Double> scores){
SynchronizedSummaryStatistics stats = new SynchronizedSummaryStatistics();
for (Double score : scores){
stats.addValue(score);
}
Double varp = stats.getPopulationVariance();
Double stdevp = FastMath.sqrt(varp);
return Precision.round(stdevp, 2);
}
}
import spock.lang.Specification
import spock.lang.Unroll
class CalculatorSpec extends Specification {
@Unroll
def "不偏標準偏差を算出する"() {
given:
def calc = new Calculator();
when:
def arg = scores.collect { it as Double };
def stdev = calc.calculateStandardDiviation(arg);
then:
stdev == result;
where:
scores | result
[1, 2, 3, 4, 5] | 1.58
[9, 8, -1, -2, 5] | 5.07
[0, 0, 0, 0, 0] | 0
}
@Unroll
def "母標準偏差を算出する"() {
given:
def calc = new Calculator();
when:
def arg = scores.collect { it as Double };
def stdevp = calc.calculatePopulationStandardDiviation(arg);
then:
stdevp == result;
where:
scores | result
[1, 2, 3, 4, 5] | 1.41
[9, 8, -1, -2, 5] | 4.53
[0, 0, 0, 0, 0] | 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment