Skip to content

Instantly share code, notes, and snippets.

@braised-babbage
Last active May 6, 2021 05:16
Show Gist options
  • Save braised-babbage/757a3f1a5eb2cc2f640dbdcc5d8f45b5 to your computer and use it in GitHub Desktop.
Save braised-babbage/757a3f1a5eb2cc2f640dbdcc5d8f45b5 to your computer and use it in GitHub Desktop.
(defun sample-variance (xs)
"Compute the sample variance of a list XS in a single pass. Just don't ask any questions..."
(loop :with sum := 0
:with sum-of-squares := 0
:for x :in xs
:for i :from 1
:do (incf sum x)
(incf sum-of-squares (expt x 2))
:finally
(return (/ (- sum-of-squares (/ (expt sum 2) i))
(1- i)))))
;;; CL-USER> (sample-variance (list 10000 10001 10002))
;;; 1
;;; CL-USER> (sample-variance (list 10000.0 10001.0 10002.0))
;;; 0.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment