I am trying to write a generic class with at type parameter T, and add a method that takes an ArrayList of type T and returns a standard deviation as type double. My program is compiling with no errors, however the standard deviation is incorrect. It is outputting the standard deviation as 2.8722813232690143, when it should be 3.0276503540974917. I cannot seem to find what I am doing wrong. Any help would be greatly appreciated!
import java.util.ArrayList;
public class MyMathClass<T extends Number> {
public ArrayList<T> myArray;
public static void main(String[] args) {
MyMathClass<Integer> intMath = new MyMathClass<>();
intMath.myArray = new ArrayList<>(10);
for (int i = 0; i < 10; i++) {
intMath.myArray.add(1);
intMath.myArray.add(2);
intMath.myArray.add(3);
intMath.myArray.add(4);
intMath.myArray.add(5);
intMath.myArray.add(6);
intMath.myArray.add(7);
intMath.myArray.add(8);
intMath.myArray.add(9);
intMath.myArray.add(10);
}
System.out.printf("standard deviation 0-9 "+ stdev(intMath.myArray));
}
public static <T extends Number> double stdev(ArrayList<T> a) {
double average = 0;
double stdev = 0;
for (T t : a)
{
average = (average + t.doubleValue());
}
average = (average / a.size());
for(T t : a)
{
stdev = (stdev + Math.pow((t.doubleValue() - average), 2));
}
stdev = (stdev / a.size());
stdev = Math.pow(stdev, .5);
return stdev;
}
}