Standard deviation

From CodeCodex

Implementations[edit]

Erlang[edit]

std_dev(List) ->
    Average = lists:sum(List) / length(List),
    F = fun(X, Sum) -> Sum + (X - Average) * (X - Average) end,
    Variance = lists:foldl(F, 0.0, List) / length(List),
    math:sqrt(Variance).

Java[edit]

import java.util.*;
import java.math.*;
public class StandardDeviation {
    public static void main(String[] args) {
 // Variables
        int[] numbers = new int[10];
        int counter, count = 5;
        double sum = 0, mean;
        double sumSquare = 0,standardDeviation=0;
 // Prompt for and read data
        Scanner in = new Scanner(System.in);
        System.out.printf("Please enter %d numbers: ",count);
 // Process based upon account type code
        for (counter = 0; counter < count; counter++){
            	numbers[counter] = in.nextInt();
            	sum += numbers[counter] ;
            	mean = sum / (count );
            	sumSquare += Math.pow((numbers[counter] - mean),2);
        }
        standardDeviation = Math.sqrt( sumSquare/count );
        System.out.printf("Standard Deviation of %d numbers entered by you is %.2f: " ,count, standardDeviation);        
    }
}

Ruby[edit]

def std_dev(ary)
  mean = ary.inject(:+).to_f / ary.size
  Math.sqrt(ary.inject(0){|sum,val| sum + (val - mean)**2} / ary.size)
end

p std_dev([1,2,3,4,5])          #=> 1.4142135623731

Tcl[edit]

package require math::statistics
::math::statistics::stdev [list 1 2 3 4 5]