how can I make sqrt(-x) example: sqrt(-1.5) work, so I don't receive a NaN? Tried to find the answer and now I understand how it works but still don't know how to do it properly. Thanks!
Context: exercise 67 (Variance) to calculate the sample variance. I base my code on example: (The average of the numbers is 3.5, so the sample variance is ((3 - 3.5)² + (2 - 3.5)² + (7 - 3.5)² + (2 - 3.5)²)/(4 - 1) ? 5,666667.)
import java.util.ArrayList;
import static java.lang.StrictMath.sqrt;
public static int sum(ArrayList<Integer> list) {
int sum = 0;
for (int item : list) {
sum+= item;
}
return sum;
}
//average from exercise 64
public static double average(ArrayList<Integer> list) {
return (double) sum(list) / list.size();
}
public static double variance(ArrayList<Integer> list) {
// write code here
double variance = 0;
int i = 0;
while (i < list.size()) {
variance = (sqrt(list.get(i) - average(list)));
i++;
}
return variance / 4-1;
// ... / n-1 for Bessel's correction
}
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(3);
list.add(2);
list.add(7);
list.add(2);
System.out.println("The variance is: " + variance(list));
}