2005-10-25 21:54:19 -04:00
|
|
|
IN: math-contrib
|
|
|
|
USING: kernel math sequences ;
|
|
|
|
|
2005-11-13 14:07:59 -05:00
|
|
|
|
|
|
|
|
2005-10-25 21:54:19 -04:00
|
|
|
: 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 /
|
|
|
|
] [
|
2005-10-31 13:13:27 -05:00
|
|
|
2 /i swap nth
|
2005-10-25 21:56:22 -04:00
|
|
|
] if ;
|
2005-10-25 21:54:19 -04:00
|
|
|
|
2005-11-13 14:07:59 -05:00
|
|
|
: minmax ( seq -- min max )
|
|
|
|
#! find the min and max of a seq in one pass
|
|
|
|
inf -inf rot [ dup pick max -rot nip pick min -rot nip ] each ;
|
|
|
|
|
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
|
|
|
|
|
|
|
: 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 ;
|