0

如何使 sqrt(-x) 示例: sqrt(-1.5) 工作,所以我没有收到 NaN?试图找到答案,现在我明白它是如何工作的,但仍然不知道如何正确地做到这一点。谢谢!

上下文:练习 67(方差)计算样本方差。我的代码基于示例:(数字的平均值为 3.5,因此样本方差为 ((3 - 3.5)² + (2 - 3.5)² + (7 - 3.5)² + (2 - 3.5)²) /(4 - 1) ? 5,666667.)

导入 java.util.ArrayList;

导入静态 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));

}
4

1 回答 1

1

此行不正确:

variance = (sqrt(list.get(i) - average(list)));

除了这个错误之外,您的方差方法还有一些严重的问题。

方差是平方和的平方根。您应该在循环内求和,并在循环外取总和的平方根。

这是我的做法:

/**
 * Created by Michael
 * Creation date 2/2/2019.
 * @link https://stackoverflow.com/questions/54494823/how-can-i-handle-nan-with-sqrt-x/54494917#54494917
 */
public class Exercise64 {

    public static void main(String[] args) {
        int [] data = { 3, 2, 7, 2 };
        System.out.println(String.format("average  : %10.4f", average(data)));
        System.out.println(String.format("variance : %10.4f", variance(data)));
        System.out.println(String.format("sqrt(var): %10.4f", Math.sqrt(variance(data)/(data.length-1))));
    }

    public static double average(int [] data) {
        double average = 0.0;
        if ((data != null) && (data.length > 0)) {
            for (int x : data) {
                average += x;
            }
            average /= data.length;
        }
        return average;
    }

    public static double variance(int [] data) {
        double variance = 0.0;
        if ((data != null) && (data.length > 1)) {
            double average = average(data);
            for (int x : data) {
                double diff = x-average;
                variance += diff*diff;
            }
        }
        return variance;
    }
}

这是我的输出:

average  :     3.5000
variance :    17.0000
sqrt(var):     2.3805

Process finished with exit code 0
于 2019-02-02T16:16:27.290 回答