Java to Calculate Standard Deviation

Calculating Standard Deviation using Java Program / Code


Standard deviation is mostly used method for measurement of diversity or variability or used in statistics related operation. Standard Deviation will be range from 0 to 1. In this Java program we used an array of values to calculate the standard deviation.

public class StandardDeviation
{

public static double StandardDeviationMean ( double[] data )
{
// sd is sqrt of sum of (values-mean) squared divided by n - 1
// Calculate the mean
double mean = 0;
final int n = data.length;
if ( n < 2 )
{
return Double.NaN;
}
for ( int i=0; i<n; i++ )
{
mean += data[i];
}
mean /= n;
// calculate the sum of squares
double sum = 0;
for ( int i=0; i<n; i++ )
{
final double v = data[i] - mean;
sum += v * v;
}
// Change to ( n - 1 ) to n if you have complete data instead of a sample.
return Math.sqrt( sum / ( n - 1 ) );
}

public static double standardDeviationCalculate ( double[] data )
{
final int n = data.length;
if ( n < 2 )
{
return Double.NaN;
}
double avg = data[0];
double sum = 0;
for ( int i = 1; i < data.length; i++ )
{
double newavg = avg + ( data[i] - avg ) / ( i + 1 );
sum += ( data[i] - avg ) * ( data [i] -newavg ) ;
avg = newavg;
}
// Change to ( n - 1 ) to n if you have complete data instead of a sample.
return Math.sqrt( sum / ( n - 1 ) );
}

public static void main ( String[] args )
{
double[] data = { 10, 100 , 50};
System.out.println(StandardDeviationMean(data));
System.out.println(standardDeviationCalculate (data));
}
}

You can use the Online standard Deviation Calculator to compare the output of the above program and to more about the calculation and theory about Standard deviation go through this Worksheet for Standard Deviation Calculation


Related Topic List of Encryption in MySQL
C Program to find Mean, Standard deviation & variance | Array example
Calculate Standard Deviation in Perl
Calculate Standard Deviation in Excel
Calculate Standard Deviation in Oracle
Java  

nScraps.com 2011   Privacy Policy  Terms of Service  Feedback