]> gitweb.factorcode.org Git - factor.git/blob - extra/math/extras/extras.factor
8b876e92b0d23cc5600f8c192d69886fd60916c2
[factor.git] / extra / math / extras / extras.factor
1 ! Copyright (C) 2012 John Benediktsson
2 ! See http://factorcode.org/license.txt for BSD license
3
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 ;
11
12 IN: math.extras
13
14 DEFER: stirling
15
16 <PRIVATE
17
18 : (stirling) ( n k -- x )
19     [ [ 1 - ] bi@ stirling ]
20     [ [ 1 - ] dip stirling ]
21     [ nip * + ] 2tri ;
22
23 PRIVATE>
24
25 MEMO: stirling ( n k -- x )
26     2dup { [ = ] [ nip 1 = ] } 2||
27     [ 2drop 1 ] [ (stirling) ] if ;
28
29 :: ramanujan ( x -- y )
30     pi sqrt x e / x ^ * x 8 * 4 + x * 1 + x * 1/30 + 1/6 ^ * ;
31
32 DEFER: bernoulli
33
34 <PRIVATE
35
36 : (bernoulli) ( p -- n )
37     [ <iota> ] [ 1 + ] bi [
38         0 [ [ nCk ] [ bernoulli * ] bi + ] with reduce
39     ] keep recip neg * ;
40
41 PRIVATE>
42
43 MEMO: bernoulli ( p -- n )
44     [ 1 ] [ (bernoulli) ] if-zero ;
45
46 : chi2 ( actual expected -- n )
47     0 [ dup 0 > [ [ - sq ] keep / + ] [ 2drop ] if ] 2reduce ;
48
49 <PRIVATE
50
51 : df-check ( df -- )
52     even? [ "odd degrees of freedom" throw ] unless ;
53
54 : (chi2P) ( chi/2 df/2 -- p )
55     [1..b) dupd n/v cum-product swap neg e^ [ v*n sum ] keep + ;
56
57 PRIVATE>
58
59 : chi2P ( chi df -- p )
60     dup df-check [ 2.0 / ] [ 2 /i ] bi* (chi2P) 1.0 min ;
61
62 <PRIVATE
63
64 : check-jacobi ( m -- m )
65     dup { [ integer? ] [ 0 > ] [ odd? ] } 1&&
66     [ "modulus must be odd positive integer" throw ] unless ;
67
68 : mod' ( x y -- n )
69     [ mod ] keep over zero? [ drop ] [
70         2dup [ sgn ] same? [ drop ] [ + ] if
71     ] if ;
72
73 PRIVATE>
74
75 : jacobi ( a m -- n )
76     check-jacobi [ mod' ] keep 1
77     [ pick zero? ] [
78         [ pick even? ] [
79             [ 2 / ] 2dip
80             over 8 mod' { 3 5 } member? [ neg ] when
81         ] while swapd
82         2over [ 4 mod' 3 = ] both? [ neg ] when
83         [ [ mod' ] keep ] dip
84     ] until [ nip 1 = ] dip 0 ? ;
85
86 <PRIVATE
87
88 : check-legendere ( m -- m )
89     dup prime? [ "modulus must be prime positive integer" throw ] unless ;
90
91 PRIVATE>
92
93 : legendere ( a m -- n )
94     check-legendere jacobi ;
95
96 : moving-average ( seq n -- newseq )
97     <clumps> [ mean ] map ;
98
99 : exponential-moving-average ( seq a -- newseq )
100     [ 1 ] 2dip '[ dupd swap - _ * + dup ] map nip ;
101
102 : moving-median ( u n -- v )
103     <clumps> [ median ] map ;
104
105 : moving-supremum ( u n -- v )
106     <clumps> [ supremum ] map ;
107
108 : moving-infimum ( u n -- v )
109     <clumps> [ infimum ] map ;
110
111 : moving-sum ( u n -- v )
112     <clumps> [ sum ] map ;
113
114 : moving-count ( ... u n quot: ( ... elt -- ... ? ) -- ... v )
115     [ <clumps> ] [ '[ _ count ] map ] bi* ; inline
116
117 : nonzero ( seq -- seq' )
118     [ zero? ] reject ;
119
120 : bartlett ( n -- seq )
121     dup 1 <= [ 1 = [ 1 1array ] [ { } ] if ] [
122         [ <iota> ] [ 1 - 2 / ] bi [
123             [ recip * ] [ >= ] 2bi [ 2 swap - ] when
124         ] curry map
125     ] if ;
126
127 : [0,2pi] ( n -- seq )
128     [ <iota> ] [ 1 - 2pi swap / ] bi v*n ;
129
130 : hanning ( n -- seq )
131     dup 1 <= [ 1 = [ 1 1array ] [ { } ] if ] [
132         [0,2pi] [ cos -0.5 * 0.5 + ] map!
133     ] if ;
134
135 : hamming ( n -- seq )
136     dup 1 <= [ 1 = [ 1 1array ] [ { } ] if ] [
137         [0,2pi] [ cos -0.46 * 0.54 + ] map!
138     ] if ;
139
140 : blackman ( n -- seq )
141     dup 1 <= [ 1 = [ 1 1array ] [ { } ] if ] [
142         [0,2pi] [
143             [ cos -0.5 * ] [ 2 * cos 0.08 * ] bi + 0.42 +
144         ] map
145     ] if ;
146
147 : nan-sum ( seq -- n )
148     0 [ dup fp-nan? [ drop ] [ + ] if ] binary-reduce ;
149
150 : nan-min ( seq -- n )
151     [ fp-nan? ] reject infimum ;
152
153 : nan-max ( seq -- n )
154     [ fp-nan? ] reject supremum ;
155
156 : fill-nans ( seq -- newseq )
157     [ first ] keep [
158         dup fp-nan? [ drop dup ] [ nip dup ] if
159     ] map nip ;
160
161 : sinc ( x -- y )
162     [ 1 ] [ pi * [ sin ] [ / ] bi ] if-zero ;
163
164 : cum-reduce ( seq identity quot: ( prev elt -- next ) -- result cum-result )
165     [ dup rot ] dip dup '[ _ curry dip dupd @ ] each ; inline
166
167 <PRIVATE
168
169 :: (gini) ( seq -- x )
170     seq natural-sort :> sorted
171     seq length :> len
172     sorted 0 [ + ] cum-reduce :> ( a b )
173     b len a * / :> c
174     1 len recip + 2 c * - ;
175
176 PRIVATE>
177
178 : gini ( seq -- x )
179     dup length 1 <= [ drop 0 ] [ (gini) ] if ;
180
181 : concentration-coefficient ( seq -- x )
182     dup length 1 <= [
183         drop 0
184     ] [
185         [ (gini) ] [ length [ ] [ 1 - ] bi / ] bi *
186     ] if ;
187
188 : herfindahl ( seq -- x )
189     [ sum-of-squares ] [ sum sq ] bi / ;
190
191 : normalized-herfindahl ( seq -- x )
192     [ herfindahl ] [ length recip ] bi
193     [ - ] [ 1 swap - / ] bi ;
194
195 : exponential-index ( seq -- x )
196     dup sum '[ _ / dup ^ ] map-product ;
197
198 : weighted-random ( histogram -- obj )
199     unzip cum-sum [ last random ] [ bisect-left ] bi swap nth ;
200
201 : unique-indices ( seq -- unique indices )
202     [ members ] keep over dup length <iota>
203     H{ } zip-as '[ _ at ] map ;
204
205 : digitize] ( seq bins -- seq' )
206     '[ _ bisect-left ] map ;
207
208 : digitize) ( seq bins -- seq' )
209     '[ _ bisect-right ] map ;
210
211 <PRIVATE
212
213 : steps ( a b length -- a b step )
214     [ 2dup swap - ] dip / ; inline
215
216 PRIVATE>
217
218 : linspace[a..b) ( a b length -- seq )
219     steps ..b) <range> ;
220
221 : linspace[a..b] ( a b length -- seq )
222     {
223         { [ dup 1 < ] [ 3drop { } ] }
224         { [ dup 1 = ] [ 2drop 1array ] }
225         [ 1 - steps <range> ]
226     } cond ;
227
228 : logspace[a..b) ( a b length base -- seq )
229     [ linspace[a..b) ] dip swap n^v ;
230
231 : logspace[a..b] ( a b length base -- seq )
232     [ linspace[a..b] ] dip swap n^v ;
233
234 : majority ( seq -- elt/f )
235     [ f 0 ] dip [
236         over zero? [ 2nip 1 ] [
237             pick = [ 1 + ] [ 1 - ] if
238         ] if
239     ] each zero? [ drop f ] when ;
240
241 : compression-lengths ( a b -- len(a+b) len(a) len(b) )
242     [ append ] 2keep [ >byte-array compress data>> length ] tri@ ;
243
244 : compression-distance ( a b -- n )
245     compression-lengths sort-pair [ - ] [ / ] bi* ;
246
247 : compression-dissimilarity ( a b -- n )
248     compression-lengths + / ;
249
250 : round-to-decimal ( x n -- y )
251     10^ [ * 0.5 over 0 > [ + ] [ - ] if truncate ] [ / ] bi ;
252
253 : round-to-step ( x step -- y )
254     [ [ / round ] [ * ] bi ] unless-zero ;
255
256 GENERIC: round-away-from-zero ( x -- y )
257
258 M: integer round-away-from-zero ; inline
259
260 M: real round-away-from-zero
261     dup 0 < [ floor ] [ ceiling ] if ;
262
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
268     ] if ; inline
269
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
274         ] reduce nip max
275     ] if ; inline
276
277 <PRIVATE
278
279 : kahan+ ( c sum elt -- c' sum' )
280     rot - 2dup + [ -rot [ - ] bi@ ] keep ; inline
281
282 PRIVATE>
283
284 : kahan-sum ( seq -- n )
285     [ 0.0 0.0 ] dip [ kahan+ ] each nip ;
286
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
290
291 <PRIVATE
292
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
295
296 : sort-partial ( x y -- x' y' )
297     2dup [ abs ] bi@ < [ swap ] when ; inline
298
299 :: partial+ ( x y -- hi lo )
300     x y + dup x - :> yr y yr - ; inline
301
302 :: partial-sums ( seq -- seq' )
303     V{ } clone :> partials
304     seq [
305         0 partials [
306             swapd sort-partial partial+ swapd
307             [ over partials set-nth 1 + ] unless-zero
308         ] each :> i
309         i partials shorten
310         [ i partials set-nth ] unless-zero
311     ] each partials ;
312
313 :: sum-exact ( partials -- n )
314     partials [ 0.0 ] [
315         ! sum from the top, stop when sum becomes inexact
316         [ 0.0 0.0 ] dip [
317             nip partial+ dup 0.0 = not
318         ] find-last drop :> ( lo n )
319
320         ! make half-even rounding work across multiple partials
321         n [ 0 > ] [ f ] if* [
322             n 1 - partials nth
323             [ 0.0 < lo 0.0 < and ]
324             [ 0.0 > lo 0.0 > and ] bi or [
325                 lo 2.0 * :> y
326                 dup y + :> x
327                 x over - :> yr
328                 y yr = [ drop x ] when
329             ] when
330         ] when
331     ] if-empty ;
332
333 PRIVATE>
334
335 : sum-floats ( seq -- n )
336     partial-sums sum-exact ;
337
338 : mobius ( n -- x )
339     group-factors values [ 1 ] [
340         dup [ 1 > ] any?
341         [ drop 0 ] [ length even? 1 -1 ? ] if
342     ] if-empty ;
343
344 : kelly ( winning-probability odds -- fraction )
345     [ 1 + * 1 - ] [ / ] bi ;
346
347 :: integer-sqrt ( m -- n )
348     m [ 0 ] [
349         dup 0 < [ non-negative-integer-expected ] when
350         bit-length 1 - 2 /i :> c
351         1 :> a!
352         0 :> d!
353         c bit-length <iota> <reversed> [| s |
354             d :> e
355             c s neg shift d!
356             a d e - 1 - shift
357             m 2 c * e - d - 1 + neg shift a /i + a!
358         ] each
359         a a sq m > [ 1 - ] when
360     ] if-zero ;