header image

Calculating Standard Deviations–the calculation

Posted by: | December 19, 2016 Comments Off on Calculating Standard Deviations–the calculation |

A while ago I saw something asking about calculating standard deviations for a set of numbers in PowerShell. You can calculate the the mean (average) of a set of numbers using Measure-Object

 

$numbers = 1..10


$mean = $numbers | Measure-Object -Average | select -ExpandProperty Average
$mean
5.5

 

To calculate the standard deviation you:

Subtract the mean of the set from each number in the set and square the difference. Then calculate the mean of those squared differences and finally take the square root of the result.

We already have the mean

 

so lets calculate the differences and square them

$sqdiffs = $numbers | foreach {[math]::Pow(($psitem - $mean), 2)}

 

The Pow static method of the math class is used to create the squares. The standard deviation (normally referred to as sigma) is calculated:

$sigma = [math]::Sqrt( ($sqdiffs | Measure-Object -Average | select -ExpandProperty Average) )
[math]::Round($sigma, 3)

 

You can calculate the mean of the squares of the differences using measure-object again. I used the Round static method of the math class to give my answer 3 decimal places.

 

Now that we can calculate the standard deviation we could turn this into a method, or a PowerShell class or even create a proxy function for Measure-Object that enables you to calculate standard deviation.

under: PowerShell Basics

Comments are closed.

Categories