Calculating Standard Deviations with Salesforce

I recently had a request that came across my desk to create a report that calculates standard deviations in Salesforce. Now I knew right off the bat that standard reporting wasn't going to be able to handle this, so I started to develop a solution with Visualforce and Apex. After looking through the docs I saw that there was no method for calculating standard deviations available to me, so I decided to create an advanced math class and do it myself.

Advanced Math Class

public class AdvancedMath 
    public static Double standardDeviation(Double[] numbers)
        //determine the sum of the range of numbers
        Double sum = 0;
        for(Double d : numbers)
            sum += d;

        //determine the mean of the range of numbers
        Double mean = sum / numbers.size();

        //for each number subtract the mean and square the result
        Double squaredDifferencesSum = 0;
        for(Double d : numbers)
            squaredDifferencesSum += Math.pow((d-mean), 2);

        //determine the mean for the squared differences
        Double squaredDifferencesMean = squaredDifferencesSum / numbers.size();

        //determine the standard deviation
        Double standardDeviation = Math.sqrt(squaredDifferencesMean);

        return standardDeviation;

From here I can now more easily determine the standard deviation of a range of numbers queried from an Object in Salesforce and display them on a nicely formatted data table with Visualforce.


//create a list of numbers to determine the standard deviation of
Double[] range = new Double[]{2,4,4,4,5,5,7,9};

//call the standard deviation method from the class we have created
Double standardDeviation = AdvancedMath.standardDeviation(range);
system.debug(standardDeviation); //should output 2.0

The above class is available as a forkable Gist here.

Hope this was helpful!

Vote on HN

comments powered by Disqus