Cumulative standard deviation: Difference between revisions

m (→‎{{header|REXX}}: changed/add comments and whitespace, changed section header comment.)
Line 813:
 
=={{header|Common Lisp}}==
{{incorrect|Common Lisp|It does not return the ''running'' standard deviation of the series. or take numbers individually.}}
<lang lisp>(defun std-dev (samples)
(let* ((n (length samples))
(mean (/ (reduce #'+ samples) n))
(tmp (mapcar (lambda (x) (expt (- x mean) 2)) samples)))
(sqrt (/ (reduce #'+ tmp) n))))
 
(format t "~a" (std-dev '(2 4 4 4 5 5 7 9)))
</lang>
 
Based on some googled web site; written ages ago.
 
<lang lisp>(defun arithmetic-average (samples)
(/ (reduce #'+ samples)
(length samples)))
 
(defun standard-deviation (samples)
(let ((mean (arithmetic-average samples)))
(sqrt (* (/ 1.0d0 (length samples))
(reduce #'+ samples
:key (lambda (x)
(expt (- x mean) 2)))))))
 
(defun make-deviator ()
(let ((numbers '()))
(lambda (x)
(push x numbers)
(standard-deviation numbers))))</lang>
 
<lang lisp>CL-USER> (loop with deviator = (make-deviator)
for i in '(2 4 4 4 5 5 7 9)
collect (list i (funcall deviator i))) ==>
((2 0.0d0)
(4 1.0d0)
(4 0.9428090415820634d0)
(4 0.8660254037844386d0)
(5 0.9797958971132713d0)
(5 1.0d0)
(7 1.3997084244475304d0)
(9 2.0d0))</lang>
 
Since we don't care about the sample values once std dev is computed, we only need to keep track of their sum and square sums, hence:<lang lisp>(defun running-stddev ()
(let ((sum 0) (sq 0) (n 0))
Line 860 ⟶ 819:
(/ (sqrt (- (* n sq) (* sum sum))) n))))
 
CL-USER> (loop with f = (running-stddev) for i in '(2 4 4 4 5 5 7 9) do
(format t "~a ~a~%" i (funcall f i)))</lang>
NIL
2 0.0
4 1.0
4 0.94280905
4 0.8660254
5 0.97979593
5 1.0
7 1.3997085
(9 2.0d0))0</lang>
 
In the REPL, one step at a time:
<lang lisp>CL-USER> (loopsetf with deviator =fn (makerunning-deviatorstddev))
#<Interpreted Closure (:INTERNAL RUNNING-STDDEV) @ #x21b9a492>
CL-USER> (funcall fn 2)
0.0
CL-USER> (funcall fn 4)
1.0
CL-USER> (funcall fn 4)
0.94280905
CL-USER> (funcall fn 4)
0.8660254
CL-USER> (funcall fn 5)
0.97979593
CL-USER> (funcall fn 5)
1.0
CL-USER> (funcall fn 7)
1.3997085
CL-USER> (funcall fn 9)
2.0
</lang>
 
=={{header|Component Pascal}}==
Anonymous user