Cumulative standard deviation: Difference between revisions
Content added Content deleted
(restored R and Racket) |
|||
Line 2,726: | Line 2,726: | ||
>>> print myStd([2,4,4,4,5,5,7,9]) |
>>> print myStd([2,4,4,4,5,5,7,9]) |
||
2.0 |
2.0 |
||
</lang> |
|||
=={{header|R}}== |
|||
===Built-in Std Dev fn=== |
|||
<lang rsplus>#The built-in standard deviation function applies the Bessel correction. To reverse this, we can apply an uncorrection. |
|||
#If na.rm is true, missing data points (NA values) are removed. |
|||
reverseBesselCorrection <- function(x, na.rm=FALSE) |
|||
{ |
|||
if(na.rm) x <- x[!is.na(x)] |
|||
len <- length(x) |
|||
if(len < 2) stop("2 or more data points required") |
|||
sqrt((len-1)/len) |
|||
} |
|||
testdata <- c(2,4,4,4,5,5,7,9) |
|||
reverseBesselCorrection(testdata)*sd(testdata) #2</lang> |
|||
===From scratch=== |
|||
<lang rsplus>#Again, if na.rm is true, missing data points (NA values) are removed. |
|||
uncorrectedsd <- function(x, na.rm=FALSE) |
|||
{ |
|||
len <- length(x) |
|||
if(len < 2) stop("2 or more data points required") |
|||
mu <- mean(x, na.rm=na.rm) |
|||
ssq <- sum((x - mu)^2, na.rm=na.rm) |
|||
usd <- sqrt(ssq/len) |
|||
usd |
|||
} |
|||
uncorrectedsd(testdata) #2</lang> |
|||
=={{header|Racket}}== |
|||
<lang racket> |
|||
#lang racket |
|||
(require math) |
|||
(define running-stddev |
|||
(let ([ns '()]) |
|||
(λ(n) (set! ns (cons n ns)) (stddev ns)))) |
|||
;; run it on each number, return the last result |
|||
(last (map running-stddev '(2 4 4 4 5 5 7 9))) |
|||
</lang> |
</lang> |
||