]> gitweb.factorcode.org Git - factor.git/blob - libs/math/statistics.factor
cfb00c015bca12547c5a7a352a48ce342e81b02f
[factor.git] / libs / math / statistics.factor
1 IN: math-contrib
2 USING: kernel math sequences ;
3
4 : mean ( seq -- n )
5     #! arithmetic mean, sum divided by length
6     [ sum ] keep length / ;
7
8 : geometric-mean ( seq -- n )
9     #! geometric mean, nth root of product
10     [ product ] keep length swap nth-root ;
11
12 : harmonic-mean ( seq -- n )
13     #! harmonic mean, reciprocal of sum of reciprocals.
14     #! positive reals only
15     0 [ recip + ] reduce recip ;
16
17 : median ( seq -- n )
18     #! middle number if odd, avg of two middle numbers if even
19     natural-sort dup length dup even? [
20         1- 2 / swap [ nth ] 2keep >r 1+ r> nth + 2 /
21     ] [
22         2 / swap nth
23     ] if ;
24
25 : range ( seq -- n )
26     #! max - min
27     minmax swap - ;
28
29 : var ( seq -- x )
30     #! variance, normalize by N-1
31     dup length 1- dup zero? [
32         0 2nip
33     ] [
34         swap [ mean ] keep 0 [ pick - sq + ] reduce nip swap /
35     ] if ;
36
37 : std ( seq -- x )
38     #! standard deviation, sqrt of variance
39     var sqrt ;