1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.hipparchus.stat.descriptive.moment;
23
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertTrue;
26
27 import org.hipparchus.stat.StatUtils;
28 import org.hipparchus.stat.descriptive.StorelessUnivariateStatisticAbstractTest;
29 import org.hipparchus.util.MathArrays;
30 import org.junit.Test;
31
32
33
34
35 public class VarianceTest extends StorelessUnivariateStatisticAbstractTest{
36
37 @Override
38 public Variance getUnivariateStatistic() {
39 return new Variance();
40 }
41
42 @Override
43 public double expectedValue() {
44 return this.var;
45 }
46
47
48 public double expectedWeightedValue() {
49 return this.weightedVar;
50 }
51
52
53
54
55 @Test
56 public void testNaN() {
57 Variance var = getUnivariateStatistic();
58 assertTrue(Double.isNaN(var.getResult()));
59 var.increment(1d);
60 assertEquals(0d, var.getResult(), 0);
61 }
62
63
64
65
66 @Test
67 public void testPopulation() {
68 double[] values = { -1.0d, 3.1d, 4.0d, -2.1d, 22d, 11.7d, 3d, 14d };
69 SecondMoment m = new SecondMoment();
70 m.incrementAll(values);
71 Variance v1 = new Variance();
72 v1 = v1.withBiasCorrection(false);
73 assertEquals(populationVariance(values), v1.evaluate(values), 1E-14);
74 v1.incrementAll(values);
75 assertEquals(populationVariance(values), v1.getResult(), 1E-14);
76 v1 = new Variance(false, m);
77 assertEquals(populationVariance(values), v1.getResult(), 1E-14);
78 v1 = new Variance(false);
79 assertEquals(populationVariance(values), v1.evaluate(values), 1E-14);
80 v1.incrementAll(values);
81 assertEquals(populationVariance(values), v1.getResult(), 1E-14);
82 }
83
84
85
86
87 protected double populationVariance(double[] v) {
88 double mean = StatUtils.mean(v);
89 double sum = 0;
90 for (double val : v) {
91 sum += (val - mean) * (val - mean);
92 }
93 return sum / v.length;
94 }
95
96 @Test
97 public void testWeightedVariance() {
98 Variance variance = getUnivariateStatistic();
99 assertEquals(expectedWeightedValue(),
100 variance.evaluate(testArray, testWeightsArray, 0, testArray.length),
101 getTolerance());
102
103
104 assertEquals(expectedValue(),
105 variance.evaluate(testArray, unitWeightsArray, 0, testArray.length),
106 getTolerance());
107
108
109
110 assertEquals(expectedValue(),
111 variance.evaluate(testArray,
112 MathArrays.normalizeArray(identicalWeightsArray, testArray.length),
113 0, testArray.length),
114 getTolerance());
115
116 }
117
118 }