Jump to content

Averages/Median: Difference between revisions

no edit summary
m (added whitespace before the TOC, added a ;See also: (bold) header.)
No edit summary
Line 2,180:
else /* an even number of elements */
median = (a(n/2) + a(trunc(n/2)+1) )/2;</lang>
 
=={{header|PowerShell}}==
This function returns an object containing the minimal amount of statistical data,
including Median, and could be modified to take input directly from the pipeline.
 
All statistical properties could easily be added to the output object.
<lang PowerShell>
function Get-Statistic
{
[CmdletBinding()]
[OutputType([double])]
Param
(
[Parameter(Mandatory=$true, Position=0)]
[ValidateNotNullOrEmpty()]
[double[]]
$Vector
)
 
$Vector = $Vector | Sort-Object
 
if ($Vector.Count % 2)
{
$median = $Vector[[Math]::Floor($Vector.Count/2)]
}
else
{
$median = ($Vector[$Vector.Count/2], $Vector[$Vector.Count/2-1] | Measure-Object -Average).Average
}
 
$Vector |
Measure-Object -Minimum -Maximum -Sum -Average |
Select-Object -Property Count, Minimum, Maximum, Sum, Average |
Add-Member -MemberType NoteProperty -Name Median -Value $median -PassThru
}
</lang>
<lang PowerShell>
Get-Statistic -Vector 5.1, 2.6, 6.4, 8.8, 4.6, 4.1
</lang>
{{Out}}
<pre>
Count : 6
Minimum : 2.6
Maximum : 8.8
Sum : 31.6
Average : 5.26666666666667
Median : 4.85
</pre>
Get the median only
<lang PowerShell>
(Get-Statistic -Vector 5.1, 2.6, 6.4, 8.8, 4.6, 4.1).Median
</lang>
{{Out}}
<pre>
4.85
</pre>
A list with an odd number of values:
<lang PowerShell>
(Get-Statistic -Vector 5.1, 2.6, 8.8, 4.6, 4.1).Median
</lang>
{{Out}}
<pre>
4.6
</pre>
 
=={{header|Prolog}}==
308

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.