! Copyright (C) 2012 John Benediktsson ! See http://factorcode.org/license.txt for BSD license USING: combinators.short-circuit grouping kernel math math.combinatorics math.functions math.order math.primes math.ranges math.statistics math.vectors memoize sequences ; IN: math.extras MEMO: sterling ( n k -- x ) 2dup { [ = ] [ nip 1 = ] } 2|| [ 2drop 1 ] [ (sterling) ] if ; MEMO: bernoulli ( p -- n ) [ 1 ] [ (bernoulli) ] if-zero ; : chi2 ( actual expected -- n ) 0 [ dup 0 > [ [ - sq ] keep / + ] [ 2drop ] if ] 2reduce ; : chi2P ( chi df -- p ) dup df-check [ 2.0 / ] [ 2 /i ] bi* (chi2P) 1.0 min ; ] [ odd? ] } 1&& [ "modulus must be odd positive integer" throw ] unless ; : mod' ( x y -- n ) [ mod ] keep over zero? [ drop ] [ 2dup [ sgn ] bi@ = [ drop ] [ + ] if ] if ; PRIVATE> : jacobi ( a m -- n ) check-jacobi [ mod' ] keep 1 [ pick zero? ] [ [ pick even? ] [ [ 2 / ] 2dip over 8 mod' { 3 5 } member? [ neg ] when ] while swapd 2over [ 4 mod' 3 = ] both? [ neg ] when [ [ mod' ] keep ] dip ] until [ nip 1 = ] dip 0 ? ; : legendere ( a m -- n ) check-legendere jacobi ; : moving-average ( seq n -- newseq ) [ mean ] map ; : exponential-moving-average ( seq a -- newseq ) [ 1 ] 2dip [ [ dupd swap - ] dip * + dup ] curry map nip ; : moving-median ( u n -- v ) [ median ] map ;