1 18 19 package org.apache.jorphan.math; 20 21 import java.io.Serializable ; 22 import java.util.ArrayList ; 23 import java.util.Collections ; 24 import java.util.List ; 25 26 import junit.framework.TestCase; 27 28 32 public class StatCalculator implements Serializable 33 { 34 List values = new ArrayList (); 35 double sum = 0; 36 double sumOfSquares = 0; 37 double mean = 0; 38 double deviation = 0; 39 int count = 0; 40 41 public void clear() 42 { 43 values.clear(); 44 sum = 0; 45 sumOfSquares = 0; 46 mean = 0; 47 deviation = 0; 48 count = 0; 49 } 50 51 public void addValue(long newValue) 52 { 53 Number val = new Long (newValue); 54 addValue(val); 55 } 56 57 public void addValue(int newValue) 58 { 59 Number val = new Integer (newValue); 60 addValue(val); 61 } 62 63 public void addValue(float newValue) 64 { 65 Number val = new Float (newValue); 66 addValue(val); 67 } 68 69 public void addValue(double newValue) 70 { 71 Number val = new Double (newValue); 72 addValue(val); 73 } 74 75 public Number getMedian() 76 { 77 return (Number ) values.get(values.size() / 2); 78 } 79 80 public double getMean() 81 { 82 return mean; 83 } 84 85 public double getStandardDeviation() 86 { 87 return deviation; 88 } 89 90 public Number getMin() 91 { 92 return (Number )values.get(0); 93 } 94 95 public Number getMax() 96 { 97 return (Number )values.get(count-1); 98 } 99 100 public int getCount() 101 { 102 return count; 103 } 104 105 public void addValue(Number val) 106 { 107 int index = Collections.binarySearch(values, val); 108 if (index >= 0 && index < values.size()) 109 { 110 values.add(index, val); 111 } 112 else if (index == values.size() || values.size() == 0) 113 { 114 values.add(val); 115 } 116 else 117 {; 118 values.add((index * (-1)) - 1, val); 119 } 120 count++; 121 double currentVal = val.doubleValue(); 122 sum += currentVal; 123 sumOfSquares += currentVal * currentVal; 124 mean = sum / count; 125 deviation = Math.sqrt( (sumOfSquares / count) - (mean * mean) ); 126 } 127 128 public static class Test extends TestCase 129 { 130 StatCalculator calc; 131 132 public Test(String name) 133 { 134 super(name); 135 } 136 137 public void setUp() 138 { 139 calc = new StatCalculator(); 140 } 141 142 public void testCalculation() 143 { 144 calc.addValue(18); 145 calc.addValue(10); 146 calc.addValue(9); 147 calc.addValue(11); 148 calc.addValue(28); 149 calc.addValue(3); 150 calc.addValue(30); 151 calc.addValue(15); 152 calc.addValue(15); 153 calc.addValue(21); 154 assertEquals(16,(int)calc.getMean()); 155 assertEquals(8.0622577F,(float)calc.getStandardDeviation(),0F); 156 assertEquals(30,calc.getMax().intValue()); 157 assertEquals(3,calc.getMin().intValue()); 158 assertEquals(15,calc.getMedian().intValue()); 159 } 160 } 161 } 162 | Popular Tags |