gpt4 book ai didi

java - 如何使用 sqrt(-x) 处理 NaN?

转载 作者:行者123 更新时间:2023-12-02 10:18:38 25 4
gpt4 key购买 nike

如何使 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));

}

最佳答案

此行不正确:

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

关于java - 如何使用 sqrt(-x) 处理 NaN?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54494823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com