1 ! Copyright (C) 2012 John Benediktsson
2 ! See http://factorcode.org/license.txt for BSD license
4 USING: accessors arrays assocs assocs.extras byte-arrays
5 combinators combinators.short-circuit compression.zlib fry
6 grouping kernel locals math math.bitwise math.combinatorics
7 math.constants math.functions math.order math.primes
8 math.primes.factors math.ranges math.ranges.private
9 math.statistics math.vectors memoize parser random sequences
10 sequences.extras sequences.private sets sorting sorting.extras ;
18 : (stirling) ( n k -- x )
19 [ [ 1 - ] bi@ stirling ]
20 [ [ 1 - ] dip stirling ]
25 MEMO: stirling ( n k -- x )
26 2dup { [ = ] [ nip 1 = ] } 2||
27 [ 2drop 1 ] [ (stirling) ] if ;
29 :: ramanujan ( x -- y )
30 pi sqrt x e / x ^ * x 8 * 4 + x * 1 + x * 1/30 + 1/6 ^ * ;
36 : (bernoulli) ( p -- n )
37 [ <iota> ] [ 1 + ] bi [
38 0 [ [ nCk ] [ bernoulli * ] bi + ] with reduce
43 MEMO: bernoulli ( p -- n )
44 [ 1 ] [ (bernoulli) ] if-zero ;
46 : chi2 ( actual expected -- n )
47 0 [ dup 0 > [ [ - sq ] keep / + ] [ 2drop ] if ] 2reduce ;
52 even? [ "odd degrees of freedom" throw ] unless ;
54 : (chi2P) ( chi/2 df/2 -- p )
55 [1..b) dupd n/v cum-product swap neg e^ [ v*n sum ] keep + ;
59 : chi2P ( chi df -- p )
60 dup df-check [ 2.0 / ] [ 2 /i ] bi* (chi2P) 1.0 min ;
64 : check-jacobi ( m -- m )
65 dup { [ integer? ] [ 0 > ] [ odd? ] } 1&&
66 [ "modulus must be odd positive integer" throw ] unless ;
69 [ mod ] keep over zero? [ drop ] [
70 2dup [ sgn ] same? [ drop ] [ + ] if
76 check-jacobi [ mod' ] keep 1
80 over 8 mod' { 3 5 } member? [ neg ] when
82 2over [ 4 mod' 3 = ] both? [ neg ] when
84 ] until [ nip 1 = ] dip 0 ? ;
88 : check-legendere ( m -- m )
89 dup prime? [ "modulus must be prime positive integer" throw ] unless ;
93 : legendere ( a m -- n )
94 check-legendere jacobi ;
96 : moving-average ( seq n -- newseq )
97 <clumps> [ mean ] map ;
99 : exponential-moving-average ( seq a -- newseq )
100 [ 1 ] 2dip '[ dupd swap - _ * + dup ] map nip ;
102 : moving-median ( u n -- v )
103 <clumps> [ median ] map ;
105 : moving-supremum ( u n -- v )
106 <clumps> [ supremum ] map ;
108 : moving-infimum ( u n -- v )
109 <clumps> [ infimum ] map ;
111 : moving-sum ( u n -- v )
112 <clumps> [ sum ] map ;
114 : moving-count ( ... u n quot: ( ... elt -- ... ? ) -- ... v )
115 [ <clumps> ] [ '[ _ count ] map ] bi* ; inline
117 : nonzero ( seq -- seq' )
120 : bartlett ( n -- seq )
121 dup 1 <= [ 1 = [ 1 1array ] [ { } ] if ] [
122 [ <iota> ] [ 1 - 2 / ] bi [
123 [ recip * ] [ >= ] 2bi [ 2 swap - ] when
127 : [0,2pi] ( n -- seq )
128 [ <iota> ] [ 1 - 2pi swap / ] bi v*n ;
130 : hanning ( n -- seq )
131 dup 1 <= [ 1 = [ 1 1array ] [ { } ] if ] [
132 [0,2pi] [ cos -0.5 * 0.5 + ] map!
135 : hamming ( n -- seq )
136 dup 1 <= [ 1 = [ 1 1array ] [ { } ] if ] [
137 [0,2pi] [ cos -0.46 * 0.54 + ] map!
140 : blackman ( n -- seq )
141 dup 1 <= [ 1 = [ 1 1array ] [ { } ] if ] [
143 [ cos -0.5 * ] [ 2 * cos 0.08 * ] bi + 0.42 +
147 : nan-sum ( seq -- n )
148 0 [ dup fp-nan? [ drop ] [ + ] if ] binary-reduce ;
150 : nan-min ( seq -- n )
151 [ fp-nan? ] reject infimum ;
153 : nan-max ( seq -- n )
154 [ fp-nan? ] reject supremum ;
156 : fill-nans ( seq -- newseq )
158 dup fp-nan? [ drop dup ] [ nip dup ] if
162 [ 1 ] [ pi * [ sin ] [ / ] bi ] if-zero ;
164 : cum-reduce ( seq identity quot: ( prev elt -- next ) -- result cum-result )
165 [ dup rot ] dip dup '[ _ curry dip dupd @ ] each ; inline
169 :: (gini) ( seq -- x )
170 seq natural-sort :> sorted
172 sorted 0 [ + ] cum-reduce :> ( a b )
174 1 len recip + 2 c * - ;
179 dup length 1 <= [ drop 0 ] [ (gini) ] if ;
181 : concentration-coefficient ( seq -- x )
185 [ (gini) ] [ length [ ] [ 1 - ] bi / ] bi *
188 : herfindahl ( seq -- x )
189 [ sum-of-squares ] [ sum sq ] bi / ;
191 : normalized-herfindahl ( seq -- x )
192 [ herfindahl ] [ length recip ] bi
193 [ - ] [ 1 swap - / ] bi ;
195 : exponential-index ( seq -- x )
196 dup sum '[ _ / dup ^ ] map-product ;
198 : weighted-random ( histogram -- obj )
199 unzip cum-sum [ last random ] [ bisect-left ] bi swap nth ;
201 : unique-indices ( seq -- unique indices )
202 [ members ] keep over dup length <iota>
203 H{ } zip-as '[ _ at ] map ;
205 : digitize] ( seq bins -- seq' )
206 '[ _ bisect-left ] map ;
208 : digitize) ( seq bins -- seq' )
209 '[ _ bisect-right ] map ;
213 : steps ( a b length -- a b step )
214 [ 2dup swap - ] dip / ; inline
218 : linspace[a..b) ( a b length -- seq )
221 : linspace[a..b] ( a b length -- seq )
223 { [ dup 1 < ] [ 3drop { } ] }
224 { [ dup 1 = ] [ 2drop 1array ] }
225 [ 1 - steps <range> ]
228 : logspace[a..b) ( a b length base -- seq )
229 [ linspace[a..b) ] dip swap n^v ;
231 : logspace[a..b] ( a b length base -- seq )
232 [ linspace[a..b] ] dip swap n^v ;
234 : majority ( seq -- elt/f )
236 over zero? [ 2nip 1 ] [
237 pick = [ 1 + ] [ 1 - ] if
239 ] each zero? [ drop f ] when ;
241 : compression-lengths ( a b -- len(a+b) len(a) len(b) )
242 [ append ] 2keep [ >byte-array compress data>> length ] tri@ ;
244 : compression-distance ( a b -- n )
245 compression-lengths sort-pair [ - ] [ / ] bi* ;
247 : compression-dissimilarity ( a b -- n )
248 compression-lengths + / ;
250 : round-to-decimal ( x n -- y )
251 10^ [ * 0.5 over 0 > [ + ] [ - ] if truncate ] [ / ] bi ;
253 : round-to-step ( x step -- y )
254 [ [ / round ] [ * ] bi ] unless-zero ;
256 GENERIC: round-away-from-zero ( x -- y )
258 M: integer round-away-from-zero ; inline
260 M: real round-away-from-zero
261 dup 0 < [ floor ] [ ceiling ] if ;
263 : monotonic-count ( seq quot: ( elt1 elt2 -- ? ) -- newseq )
264 over empty? [ 2drop { } ] [
265 [ 0 swap unclip-slice swap ] dip '[
266 [ @ [ 1 + ] [ drop 0 ] if ] keep over
267 ] { } map-as 2nip 0 prefix
270 : max-monotonic-count ( seq quot: ( elt1 elt2 -- ? ) -- n )
271 over empty? [ 2drop 0 ] [
272 [ 0 swap unclip-slice swap 0 ] dip '[
273 [ swapd @ [ 1 + ] [ max 0 ] if ] keep swap
279 : kahan+ ( c sum elt -- c' sum' )
280 rot - 2dup + [ -rot [ - ] bi@ ] keep ; inline
284 : kahan-sum ( seq -- n )
285 [ 0.0 0.0 ] dip [ kahan+ ] each nip ;
287 : map-kahan-sum ( ... seq quot: ( ... elt -- ... n ) -- ... n )
288 [ 0.0 0.0 ] 2dip [ 2dip rot kahan+ ] curry
289 [ -rot ] prepose each nip ; inline
293 ! Adaptive Precision Floating-Point Arithmetic and Fast Robust Geometric Predicates
294 ! www-2.cs.cmu.edu/afs/cs/project/quake/public/papers/robust-arithmetic.ps
296 : sort-partial ( x y -- x' y' )
297 2dup [ abs ] bi@ < [ swap ] when ; inline
299 :: partial+ ( x y -- hi lo )
300 x y + dup x - :> yr y yr - ; inline
302 :: partial-sums ( seq -- seq' )
303 V{ } clone :> partials
306 swapd sort-partial partial+ swapd
307 [ over partials set-nth 1 + ] unless-zero
310 [ i partials set-nth ] unless-zero
313 :: sum-exact ( partials -- n )
315 ! sum from the top, stop when sum becomes inexact
317 nip partial+ dup 0.0 = not
318 ] find-last drop :> ( lo n )
320 ! make half-even rounding work across multiple partials
321 n [ 0 > ] [ f ] if* [
323 [ 0.0 < lo 0.0 < and ]
324 [ 0.0 > lo 0.0 > and ] bi or [
328 y yr = [ drop x ] when
335 : sum-floats ( seq -- n )
336 partial-sums sum-exact ;
339 group-factors values [ 1 ] [
341 [ drop 0 ] [ length even? 1 -1 ? ] if
344 : kelly ( winning-probability odds -- fraction )
345 [ 1 + * 1 - ] [ / ] bi ;
347 :: integer-sqrt ( m -- n )
349 dup 0 < [ non-negative-integer-expected ] when
350 bit-length 1 - 2 /i :> c
353 c bit-length <iota> <reversed> [| s |
357 m 2 c * e - d - 1 + neg shift a /i + a!
359 a a sq m > [ 1 - ] when