Averages/Median: Difference between revisions
Content added Content deleted
m (Added link to definition) |
m (Add link to Mean) |
||
Line 1: | Line 1: | ||
{{task|Arithmetic operations}}Write a program to find the [[wp:Median|median]] value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but ''must'' handle the case where there are an even number of elements. |
{{task|Arithmetic operations}}Write a program to find the [[wp:Median|median]] value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but ''must'' handle the case where there are an even number of elements. |
||
===See also=== |
|||
* [[Mean]] |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
Revision as of 10:51, 12 June 2009
Averages/Median
You are encouraged to solve this task according to the task description, using any language you may know.
You are encouraged to solve this task according to the task description, using any language you may know.
Write a program to find the median value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.
See also
Tcl
<lang tcl>proc median args {
set list [lsort -real $args] set len [llength $list] # Odd number of elements if {$len & 1} { return [lindex $list [expr {($len-1)/2}]] } # Even number of elements set idx2 [expr {$len/2}] set idx1 [expr {$idx2-1}] return [expr { ([lindex $list $idx1] + [lindex $list $idx2])/2.0 }]
}
puts [median 3.0 4.0 1.0 -8.4 7.2 4.0 1.0 1.2]; # --> 2.1</lang>