Posted By

vinotht on 06/17/11


Tagged

math


Versions (?)

Calculate SD


 / Published in: Java
 

this simple program will calculate the SD(standard deviation) for the given input. Know more theory about standard deviation @ Standard Deviation Calculator

  1. public class StandardDeviation{
  2. public static double mean ( double[] data )
  3.  
  4. {
  5.  
  6. double mean = 0;
  7. final int n = data.length;
  8. if ( n < 2 )
  9. return Double.NaN;
  10. for ( int i=0; i<n; i++ )
  11. mean += data[i];
  12. mean /= n;
  13. double sum = 0;
  14. for ( int i=0; i<n; i++ )
  15. {
  16. final double v = data[i] - mean;
  17. sum += v * v;
  18. }
  19. return Math.sqrt( sum / ( n - 1 ) );
  20. }
  21. public static double sd ( double[] data ){
  22.  
  23. final int n = data.length;
  24.  
  25. if ( n < 2 )
  26. return Double.NaN;
  27. double avg = data[0];
  28. double sum = 0;
  29. for ( int i = 1; i < data.length; i++ )
  30. {
  31. double newavg = avg + ( data[i] - avg ) / ( i + 1 );
  32. sum += ( data[i] - avg ) * ( data [i] -newavg ) ;
  33. avg = newavg;
  34. }
  35. return Math.sqrt( sum / ( n - 1 ) );
  36. }
  37. public static void main ( String[] args )
  38. {
  39. double[] data = { 10, 100 , 50};
  40. System.out.println(mean(data));
  41. System.out.println(sd (data));
  42. }
  43. }

Report this snippet  

You need to login to post a comment.