[英]I want to find the Variance and Standard-Deviation using a 2D array. I did the program but the output coming is incorrect
我想使用 2D 數組找到方差和標准差我做了這個程序,但是 output 通信不正確。 請幫助我應該做什么/修改它以獲得所需的 output。
輸入
3 4
1 0 1 1 1 1 1 1 1 1 1 1
解決方案 output
0.07513148009038192
0.27410122234383033
預期 output
0.0764
0.2764
我的程序:
import java.util.*;
import java.text.DecimalFormat;
public class Source {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int m = s.nextInt();
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
arr[i][j] = s.nextInt();
varianceAndStandardDeviation(arr, n, m);
}
// Method for calculating variance
static void varianceAndStandardDeviation(int arr[][], int n, int m) {
// Write your code here
double[][] diff = new double[n][m];
double avg = 0f;
double var = 0f;
double std_dev = 0f;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
{
avg = (avg + arr[i][j]);
avg = avg/(n*m);
diff[i][j] = (avg - arr[i][j]);
var = ((diff[i][j] * diff[i][j])/((n*m)-1));
std_dev = Math.pow(var, 0.5);
}
System.out.println(var);
System.out.println(std_dev);
}
}
進行 2 次傳遞:一次計算平均值,另一次計算方差:
import java.util.Scanner;
public class Source {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int m = s.nextInt();
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
arr[i][j] = s.nextInt();
varianceAndStandardDeviation(arr, n, m);
}
// Method for calculating variance
static void varianceAndStandardDeviation(int arr[][], int n, int m) {
double avg = 0;
double variance = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
avg += arr[i][j];
avg /= n * m;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
variance += Math.pow((arr[i][j] - avg), 2);
variance /= n * m;
System.out.printf("%.4f%n", variance);
System.out.printf("%.4f%n", Math.sqrt(variance));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.