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

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.

This entry was posted in Powershell Basics. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s