【问题标题】:How can I handle NaN with sqrt(-x)?如何使用 sqrt(-x) 处理 NaN?
【发布时间】:2019-02-02 16:04:54
【问题描述】:

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

上下文:exercise 67 (Variance) 计算样本方差。 我的代码基于示例: (数字的平均值为 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));

}

【问题讨论】:

  • sqrt - 平方根,你想要的是 2 的幂 (Math.pow)
  • 你不能。您需要一个返回复数的平方根函数。标准函数只处理实数值。平方和如何产生负数?根据定义,正方形是正定的。

标签: java sqrt math.sqrt


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-25
    • 2018-09-02
    • 2020-04-19
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多