header image

Calculating Standard Deviation – the class

Posted by: | December 20, 2016 Comments Off on Calculating Standard Deviation – the class |

You’ve seen how to calculate standard deviation and how to turn that calculation into a PowerShell function. This time we’ll use the calculation to create a class:

class stats {

static [double] StandardDeviation ([double[]]$numbers) {

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

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

return [math]::Round($sigma, 3)

}
}

 

Name the class stats. We’ll create a static method on the class that will calculate the Standard Deviation. The method takes an array of doubles as input – integers are converted automatically to double.

 

The calculation is the same as before. Just add the return keyword to ensure you actually get the output. Using return is mandatory in PowerShell classes.

 

Because its a static class you don’t need to create an instance of the class – just use it directly:

$numbers = 1..10
[stats]::StandardDeviation($numbers)
[stats]::StandardDeviation(1..10)

under: PowerShell Basics

Comments are closed.

Categories