2 ms·
Calculating the mean and variance with one pass
- albertcardona 16y agoVery nice, thanks for sharing! For my own purposes I implemented the function in clojure, which I find more readable. Destructuring and literal vectors are great assets of clojure. Autopromotion to avoid overflow (as in common lisp) is also great. (defn mean-variance [data] (let [square (fn [x] (* x x)) [n xs x2s] (reduce (fn [accum xi] [(inc (accum 0)) (+ (accum 1) xi) (+ (accum 2) (square xi))]) [0 0 0] data) mu (/ xs n)] [mu (- (/ x2s n) (square mu))]))