1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.math.stat.descriptive.moment;
18
19 import junit.framework.Test;
20 import junit.framework.TestSuite;
21
22 import org.apache.commons.math.stat.descriptive.StorelessUnivariateStatisticAbstractTest;
23 import org.apache.commons.math.stat.descriptive.UnivariateStatistic;
24
25
26
27
28
29
30 public class StandardDeviationTest extends StorelessUnivariateStatisticAbstractTest{
31
32 protected StandardDeviation stat;
33
34
35
36
37 public StandardDeviationTest(String name) {
38 super(name);
39 }
40
41
42
43
44 @Override
45 public UnivariateStatistic getUnivariateStatistic() {
46 return new StandardDeviation();
47 }
48
49 public static Test suite() {
50 TestSuite suite = new TestSuite(StandardDeviationTest.class);
51 suite.setName("StandardDeviation Tests");
52 return suite;
53 }
54
55
56
57
58 @Override
59 public double expectedValue() {
60 return this.std;
61 }
62
63
64
65
66
67 public void testNaN() {
68 StandardDeviation std = new StandardDeviation();
69 assertTrue(Double.isNaN(std.getResult()));
70 std.increment(1d);
71 assertEquals(0d, std.getResult(), 0);
72 }
73
74
75
76
77 public void testPopulation() {
78 double[] values = {-1.0d, 3.1d, 4.0d, -2.1d, 22d, 11.7d, 3d, 14d};
79 double sigma = populationStandardDeviation(values);
80 SecondMoment m = new SecondMoment();
81 m.evaluate(values);
82 StandardDeviation s1 = new StandardDeviation();
83 s1.setBiasCorrected(false);
84 assertEquals(sigma, s1.evaluate(values), 1E-14);
85 s1.incrementAll(values);
86 assertEquals(sigma, s1.getResult(), 1E-14);
87 s1 = new StandardDeviation(false, m);
88 assertEquals(sigma, s1.getResult(), 1E-14);
89 s1 = new StandardDeviation(false);
90 assertEquals(sigma, s1.evaluate(values), 1E-14);
91 s1.incrementAll(values);
92 assertEquals(sigma, s1.getResult(), 1E-14);
93 }
94
95
96
97
98 protected double populationStandardDeviation(double[] v) {
99 double mean = new Mean().evaluate(v);
100 double sum = 0;
101 for (int i = 0; i < v.length; i++) {
102 sum += (v[i] - mean) * (v[i] - mean);
103 }
104 return Math.sqrt(sum / v.length);
105 }
106
107 }