Version 2 of Numeric Statistics From a List

Updated 2017-12-21 09:41:49 by DEC

At a certain point I needed the maximum, minimum and mean of a list. Instead of calculating them one after the other I created a proc that calculates everything in one go. And also length and sum.

This is the proc:

proc listNumericStats {thisList} {
    set length [llength ${thisList}]
    if {${length} == 0} {
        error "List cannot be empty"
    }
    set max [lindex ${thisList} 0]
    set min ${max}
    set sum 0.
    foreach element ${thisList} {
        set sum [expr {${sum} + ${element}}]
        if {${element} < ${min}} {
            set min ${element}
        } elseif {${element} > ${max}} {
            set max ${element}
        }
    }
    dict set stats length ${length}
    dict set stats max    ${max}
    dict set stats mean   [expr {${sum} / ${length}}]
    dict set stats min    ${min}
    dict set stats sum    ${sum}
    return ${stats}
}

DEC:That sounds over kill to me

set aList [ lsort -real $anotherList]
set max [ lindex $aList end]
set min [ lindex $aList 0]
set sum [expr {[join $aList "+"]}]
set len [llength $aList ] 
set mean [ expr {$sum/$len}]

DEC:I would avoid looping over a list at the script level if you can

KPV: Also checkout ::math::statistics::basic-stats