factor/libs/math/statistics.factor

63 lines
1.6 KiB
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 ;
: ((r)) ( mean(x) mean(y) {x} {y} -- (r) )
! finds sigma((xi-mean(x))(yi-mean(y))
0 [ [ >r pick r> swap - ] 2apply * + ] 2reduce 2nip ;
: (r) ( mean(x) mean(y) {x} {y} sx sy -- r )
* recip >r [ ((r)) ] keep length 1- / r> * ;
: [r] ( {{x,y}...} -- mean(x) mean(y) {x} {y} sx sy )
unpair [ [ [ mean ] 2apply ] 2keep ] 2keep [ std ] 2apply ;
: r ( {{x,y}...} -- r )
[r] (r) ;
: r^2 ( {{x,y}...} -- r )
r sq ;
: least-squares ( {{x,y}...} -- alpha beta )
[r] >r >r >r >r 2dup r> r> r> r>
! stack is mean(x) mean(y) mean(x) mean(y) {x} {y} sx sy
[ (r) ] 2keep ! stack is mean(x) mean(y) r sx sy
swap / * ! stack is mean(x) mean(y) beta
[ swapd * - ] keep ;