DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Calculate SD

06.20.2011
| 2696 views |
  • submit to reddit
        this simple program will calculate the SD(standard deviation) for the given input. 

public class StandardDeviation{
   public static double mean ( double[] data )

      {

      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;
      double sum = 0;
      for ( int i=0; i<n; i++ )
         {
         final double v = data[i] - mean;
         sum += v * v;
         }
      return Math.sqrt( sum / ( n - 1 ) );
      }
   public static double sd  ( 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;
         }
      return Math.sqrt( sum / ( n - 1 ) );
      }
   public static void main ( String[] args )
      {
      double[] data = { 10, 100 , 50};
      System.out.println(mean(data));
      System.out.println(sd (data));
      }
   }
Source at <a href="http://ncalculators.com/statistics/mean-standard-deviation-calculator.htm">Standard Deviation Calculator</a>