factor/contrib/math/statistics.factor

40 lines
945 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.
2005-11-16 19:40:45 -05:00
#! positive reals only
0 [ recip + ] reduce recip ;
2005-10-31 00:41:17 -05:00
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
natural-sort dup length dup even? [
1- 2 / swap [ nth ] 2keep >r 1+ r> nth + 2 /
2005-10-25 21:56:22 -04:00
] [
2 / swap nth
2005-10-25 21:56:22 -04:00
] if ;
2005-10-25 21:54:19 -04:00
: range ( seq -- n )
2005-10-25 21:56:22 -04:00
#! max - min
2005-11-13 14:07:59 -05:00
minmax swap - ;
2005-10-25 21:54:19 -04:00
2006-08-18 12:57:46 -04:00
: var ( seq -- x )
2005-10-25 21:56:22 -04:00
#! variance, normalize by N-1
dup length 1- dup zero? [
2005-10-25 21:56:22 -04:00
0 2nip
] [
2005-11-16 19:40:45 -05:00
swap [ mean ] keep 0 [ pick - sq + ] reduce nip swap /
2005-10-25 21:56:22 -04:00
] if ;
2005-10-25 21:54:19 -04:00
2006-08-18 12:57:46 -04:00
: std ( seq -- x )
2005-10-25 21:56:22 -04:00
#! standard deviation, sqrt of variance
var sqrt ;