Skip to content

Instantly share code, notes, and snippets.

@llasram
Forked from timvisher/-
Last active July 30, 2017 17:38
Show Gist options
  • Save llasram/5860685 to your computer and use it in GitHub Desktop.
Save llasram/5860685 to your computer and use it in GitHub Desktop.
(defn ^:private mean-sd-step
[[n m s] ^double x]
(let [n (long n), m (double m), s (double s)
n (inc n), d (- x m), m (+ m (/ d n)), s (+ s (* d (- x m)))]
[n m s]))
(defn mean-sd
"Calculate mean and (sample) standard-deviation of `vals`."
[vals]
(let [[n m s] (reduce mean-sd-step [0 0.0 0.0] vals)]
[m (if (<= n 1) 0.0 (Math/sqrt (/ s (dec n))))]))
(mean-sd (range 1 100))
;; => [50.0 28.722813232690143]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment