【发布时间】: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) -
你不能。您需要一个返回复数的平方根函数。标准函数只处理实数值。平方和如何产生负数?根据定义,正方形是正定的。