Created
November 27, 2013 18:47
-
-
Save ayapi/7681028 to your computer and use it in GitHub Desktop.
不偏標準偏差と母標準偏差をApacheCommonsMathのStatで算出する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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