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)
Advertisements
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:

WordPress.com Logo

You are commenting using your WordPress.com 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