java - 如何使用 sqrt(-x) 处理 NaN?
问题描述
如何使 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));
}
解决方案
此行不正确:
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
推荐阅读
- html - html 中的滞后 gif... 有时
- javascript - WKWebView 的 evaluateJavaScript 的返回类型
- c# - 可观察的:在源完成之前获取间隔的最新值
- linux - 如何在 docker 容器中安装我的 python 代码?
- single-spa - 单个 SPA JSON 布局定义
- powerbi - PowerBI DAX 比较操作中的错误不支持将文本类型的值与整数类型的值进行比较
- javascript - 是否可以在 firestore 的 delete() 中使用“哪里”?我正在寻找一种删除范围文档的方法
- laravel - 上传存储中的文件
- google-sheets - 我可以在查询选择语句的另一个选项卡中使用单元格引用吗?
- c - 并行化 BW 和 FW 算法的最佳方法