factor/contrib/math/statistics.factor

40 lines
937 B
Factor
Raw Normal View History

2005-10-25 21:54:19 -04:00
IN: math-contrib
USING: kernel math sequences ;
: mean ( seq -- n )
2005-10-25 21:56:22 -04:00
#! arithmetic mean, sum divided by length
2005-10-25 21:54:19 -04:00
[ sum ] keep length / ;
2005-10-31 00:41:17 -05:00
: geometric-mean ( seq -- n )
2005-10-25 21:56:22 -04:00
#! geometric mean, nth root of product
[ product ] keep length swap nth-root ;
2005-10-25 21:54:19 -04:00
2005-10-31 00:41:17 -05:00
: harmonic-mean ( seq -- n )
#! harmonic mean, reciprocal of sum of reciprocals.
[ recip ] map sum recip ;
2005-10-25 21:54:19 -04:00
: median ( seq -- n )
2005-10-25 21:56:22 -04:00
#! middle number if odd, avg of two middle numbers if even
2005-10-25 21:54:19 -04:00
number-sort dup length dup even? [
2005-10-25 21:56:22 -04:00
1+ 2 /i dup 1- rot [ nth ] keep swapd nth + 2 /
] [
2 / swap nth
] if ;
2005-10-25 21:54:19 -04:00
: range ( seq -- n )
2005-10-25 21:56:22 -04:00
#! max - min
2005-10-31 00:41:17 -05:00
dup first 2dup [ min ] reduce >r [ max ] reduce r> - ;
2005-10-25 21:54:19 -04:00
: var ( seq -- )
2005-10-25 21:56:22 -04:00
#! variance, normalize by N-1
dup length 1- dup 0 = [
0 2nip
] [
swap [ mean ] keep [ over - sq ] map sum nip swap /
] if ;
2005-10-25 21:54:19 -04:00
: std
2005-10-25 21:56:22 -04:00
#! standard deviation, sqrt of variance
var sqrt ;
2005-10-25 21:54:19 -04:00