factor/extra/math/statistics/statistics.factor

72 lines
1.9 KiB
Factor
Raw Normal View History

2008-10-03 03:19:03 -04:00
! Copyright (C) 2008 Doug Coleman, Michael Judge.
! See http://factorcode.org/license.txt for BSD license.
2008-11-09 17:16:30 -05:00
USING: arrays kernel math math.analysis math.functions sequences sequences.lib
sorting ;
2007-09-20 18:09:08 -04:00
IN: math.statistics
: mean ( seq -- n )
#! arithmetic mean, sum divided by length
2008-09-22 22:31:15 -04:00
[ sum ] [ length ] bi / ;
2007-09-20 18:09:08 -04:00
: geometric-mean ( seq -- n )
#! geometric mean, nth root of product
2008-09-22 22:31:15 -04:00
[ length ] [ product ] bi nth-root ;
2007-09-20 18:09:08 -04:00
: harmonic-mean ( seq -- n )
#! harmonic mean, reciprocal of sum of reciprocals.
#! positive reals only
2008-09-22 22:31:15 -04:00
[ recip ] sigma recip ;
2007-09-20 18:09:08 -04:00
: median ( seq -- n )
#! middle number if odd, avg of two middle numbers if even
2008-11-09 17:16:30 -05:00
natural-sort dup length even? [
[ midpoint@ dup 1- 2array ] keep nths mean
2007-09-20 18:09:08 -04:00
] [
2008-11-09 17:16:30 -05:00
[ midpoint@ ] keep nth
2007-09-20 18:09:08 -04:00
] if ;
: range ( seq -- n )
#! max - min
minmax swap - ;
: var ( seq -- x )
#! variance, normalize by N-1
dup length 1 <= [
drop 0
] [
2008-01-09 17:36:30 -05:00
[ [ mean ] keep [ - sq ] with sigma ] keep
2007-09-20 18:09:08 -04:00
length 1- /
] if ;
: std ( seq -- x )
#! standard deviation, sqrt of variance
var sqrt ;
: ste ( seq -- x )
#! standard error, standard deviation / sqrt ( length of sequence )
2008-11-09 17:16:30 -05:00
[ std ] [ length ] bi sqrt / ;
2007-09-20 18:09:08 -04:00
: ((r)) ( mean(x) mean(y) {x} {y} -- (r) )
! finds sigma((xi-mean(x))(yi-mean(y))
2008-11-09 17:16:30 -05:00
0 [ [ [ pick ] dip swap - ] bi@ * + ] 2reduce 2nip ;
2007-09-20 18:09:08 -04:00
: (r) ( mean(x) mean(y) {x} {y} sx sy -- r )
2008-11-09 17:16:30 -05:00
* recip [ [ ((r)) ] keep length 1- / ] dip * ;
2007-09-20 18:09:08 -04:00
: [r] ( {{x,y}...} -- mean(x) mean(y) {x} {y} sx sy )
2008-03-29 21:36:58 -04:00
first2 [ [ [ mean ] bi@ ] 2keep ] 2keep [ std ] bi@ ;
2007-09-20 18:09:08 -04:00
: 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 ;