简体   繁体   中英

How to calculate the standard deviation for an array column in Java?

Here is an array:

int[][] array1 = {
                      {1,2},
                      {3,4},
                      {5,6},
                      {7,8},
                      {9,10}
                 };

My goal is to use the array above to find the standard deviation for the column:

public double stdevCol(int[][] array, int col)
{

}

Here is my standard deviation function for the total:

public double stdev2D(int[][] array)
{
    int counter =0;
    double mean = mean2D(array);
    double sumOfSq =0;
    for(int i = 0; i<array.length; i++)
    {
        for(int j = 0 ; j< array[i].length; j++)
        {
            sumOfSq += Math.pow(array[i][j] - mean, 2.0);
            counter++;
        }
    }
    return Math.sqrt(sumOfSq/counter);
}

My question: If using the total as a reference point, would I switch instead of array[i].length to (array,col).length ?

Experimental code

{
    int counter =0;
    double mean = meanCol(array);
    double sumOfSq =0;
    for(int i = 0; i<array[col].length; i++)
    {
        sumOfSq += Math.pow(array[col].length - mean, 2.0);
        counter++;
    }
    return Math.sqrt(sumOfSq/counter);
}
import java.io.*;


class GFG {


// Function for calculating
// variance
static double variance(double a[], int n) {
    // Compute mean (average of elements)
    double sum = 0;
    
    for (int i = 0; i < n; i++){
        sum += a[i];
    }
    double mean = (double)sum /(double)n;
 
    // Compute sum squared differences with mean.
    double sqDiff = 0;
    for (int i = 0; i < n; i++){
        sqDiff += (a[i] - mean) *(a[i] - mean);
     }
    return (double)sqDiff / n;
}
 
static double standardDeviation(double arr[], int n) {
    return Math.sqrt(variance(arr, n));
}
 
// Driver Code
public static void main (String[] args) {
 
double arr[] = {600, 470, 170, 430, 300};
int n = arr.length;
 
System.out.println( "Variance: " + variance(arr, n));
System.out.println ("Standard Deviation: " + standardDeviation(arr, n));

}
}

All credits go to vt_m of course, I have just changed his formatting

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM