 PoshCode Archive  Artifact Content

Artifact 14d049a89b6b195e36c8fb9bb169f953443de888e1e175781093c3e4965b2c50:

• File Standard-Deviation.ps1 — part of check-in [08c8b0b89e] at 2018-06-10 14:19:56 on branch trunk — The most accurate way of calculating Standard Deviation (according to the experts) is a method created by B.P.Welford, which is detailed in-depth in Donald Knuths Art of computer programming. (user: Richard Young size: 1791)

```# encoding: ascii
# api: powershell
# title: Standard Deviation
# description: The most accurate way of calculating Standard Deviation (according to the experts) is a method created by B.P.Welford, which is detailed in-depth in Donald Knuth’s ‘Art of computer programming’.
# version: 0.0
# type: function
# author: Richard Young
# function: Get-StandardDeviation
# x-poshcode-id: 6720
# x-archived: 2017-02-12T12:36:03
# x-published: 2017-02-06T11:24:00
#
# Test as follows:
# Create some data
# \$data = (50.0, 45.0, 55.0, 58.0, 43.0, 49.0, 50.0)</code>
# Run one of the following options:
# Get-StandardDeviation -Values \$data
# \$data | Get-StandardDeviation
#
function Get-StandardDeviation {
[CmdletBinding()]
Param (
# Array of double values
[Parameter(Mandatory=\$true, ValueFromPipelineByPropertyName=\$true,ValueFromPipeline=\$true)]
[ValidateNotNullOrEmpty()]
[double[]]\$Values
)
Begin {
\$count=0.0
\$mean=0.0
\$sum=0.0
}#begin

Process {
foreach (\$value in \$values) {
++\$count
\$delta = \$mean + ((\$value - \$mean) / \$count)
\$sum += (\$value - \$mean) * (\$value - \$delta)
\$mean = \$delta
}#foreach
} # process

End {
\$VariancePopulation = \$sum/(\$count)
\$VarianceSample = \$sum/(\$count-1)
\$obj=[PSCustomObject]@{
"VariancePopulation" = \$VariancePopulation
"VarianceSample" = \$VarianceSample
"STDEVPopulation" = [Math]::Sqrt(\$VariancePopulation)
"STDEVSample" = [Math]::Sqrt(\$VarianceSample)
"Mean" = \$mean
"Count" = \$count
}#obj
Write-Output \$obj
} #end

}#function

```