add a mode word

db4
Doug Coleman 2009-05-24 15:45:25 -05:00
parent 30a623c531
commit 86a1b06034
2 changed files with 11 additions and 1 deletions

View File

@ -13,6 +13,9 @@ IN: math.statistics.tests
[ 2 ] [ { 1 2 3 } median ] unit-test [ 2 ] [ { 1 2 3 } median ] unit-test
[ 5/2 ] [ { 1 2 3 4 } median ] unit-test [ 5/2 ] [ { 1 2 3 4 } median ] unit-test
[ 1 ] [ { 1 } mode ] unit-test
[ 3 ] [ { 1 2 3 3 3 4 5 6 76 7 2 21 1 3 3 3 } mode ] unit-test
[ { } median ] must-fail [ { } median ] must-fail
[ { } upper-median ] must-fail [ { } upper-median ] must-fail
[ { } lower-median ] must-fail [ { } lower-median ] must-fail

View File

@ -2,7 +2,7 @@
! See http://factorcode.org/license.txt for BSD license. ! See http://factorcode.org/license.txt for BSD license.
USING: arrays combinators kernel math math.analysis USING: arrays combinators kernel math math.analysis
math.functions math.order sequences sorting locals math.functions math.order sequences sorting locals
sequences.private ; sequences.private assocs fry ;
IN: math.statistics IN: math.statistics
: mean ( seq -- x ) : mean ( seq -- x )
@ -56,6 +56,13 @@ IN: math.statistics
: median ( seq -- x ) : median ( seq -- x )
dup length odd? [ lower-median ] [ medians + 2 / ] if ; dup length odd? [ lower-median ] [ medians + 2 / ] if ;
: frequency ( seq -- hashtable )
H{ } clone [ '[ _ inc-at ] each ] keep ;
: mode ( seq -- x )
frequency >alist
[ ] [ [ [ second ] bi@ > ] 2keep ? ] map-reduce first ;
: minmax ( seq -- min max ) : minmax ( seq -- min max )
#! find the min and max of a seq in one pass #! find the min and max of a seq in one pass
[ 1/0. -1/0. ] dip [ [ min ] [ max ] bi-curry bi* ] each ; [ 1/0. -1/0. ] dip [ [ min ] [ max ] bi-curry bi* ] each ;