I recently published my Measure-ScriptBlock function, where you can set how many times you want to take measurements of your code block, and get the mean value (average) calculated before output. That is all and well, but running it I could see that sometimes there would be some measurements that would spike and make the mean value higher than it really “should” be.
I started thinking about how it would be neat if I could calculate the trimmed mean instead. When calculating a trimmed mean, you remove (trim) a certain portion at the beginning and end of your (sorted) set, and then calculate the mean of the remaining values.
The idea is to use this function in my Measure-ScriptBlock function, but I thought I’d release it on it’s own as well. Might be others that can find it useful as well.
Enjoy.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Get-TrimmedMean { | |
<# | |
.SYNOPSIS | |
Function to calculate the trimmed mean of a set of numbers. | |
.DESCRIPTION | |
Function to calculate the trimmed mean of a set of numbers. | |
The default trim percent is 25, which when used will calculate the Interquartile Mean of the number set. | |
Use the TrimPercent parameter to set the trim percent as needed. | |
.EXAMPLE | |
[double[]]$dataSet = 8, 3, 7, 1, 3, 9 | |
Get-TrimmedMean -NumberSet $dataSet | |
Calculate the trimmed mean of the number set, using the default trim percent of 25. | |
.NOTES | |
Author: Øyvind Kallstad | |
Date: 29.10.2014 | |
Version: 1.0 | |
#> | |
[CmdletBinding()] | |
param ( | |
[Parameter(Mandatory)] | |
[double[]] $NumberSet, | |
[Parameter()] | |
[ValidateRange(1,100)] | |
[int] $TrimPercent = 25 | |
) | |
try { | |
# collect the number set into an arraylist and sort it | |
$orderedSet = New-Object System.Collections.ArrayList | |
$orderedSet.AddRange($NumberSet) | |
$orderedSet.Sort() | |
# calculate the trim count | |
$numberSetLength = $orderedSet.Count | |
$trimmedMean = $TrimPercent/100 | |
$trimmedCount = [Math]::Floor($trimmedMean * $numberSetLength) | |
# subtract trim count from top and bottom of the number set | |
[double[]]$trimmedSet = $orderedSet[$trimmedCount..($numberSetLength – ($trimmedCount+1))] | |
# calculate the mean of the trimmed set | |
Write-Output ($trimmedSet | Measure-Object –Average | Select-Object –ExpandProperty Average) | |
} | |
catch { | |
Write-Warning $_.Exception.Message | |
} | |
} |