EasyPG 1.07 Released
[packages] / xemacs-packages / calc / calc-comb.el
1 ;;; calc-comb.el --- combinatoric functions for Calc
2
3 ;; Copyright (C) 1990-1993, 2001-2015 Free Software Foundation, Inc.
4
5 ;; Author: David Gillespie <daveg@synaptics.com>
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software: you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation, either version 3 of the License, or
12 ;; (at your option) any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
21
22 ;;; Commentary:
23
24 ;;; Code:
25
26 ;; This file is autoloaded from calc-ext.el.
27
28 (require 'calc-ext)
29 (require 'calc-macs)
30
31 (defconst math-primes-table
32   [2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89
33      97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181
34      191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277
35      281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383
36      389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487
37      491 499 503 509 521 523 541 547 557 563 569 571 577 587 593 599 601
38      607 613 617 619 631 641 643 647 653 659 661 673 677 683 691 701 709
39      719 727 733 739 743 751 757 761 769 773 787 797 809 811 821 823 827
40      829 839 853 857 859 863 877 881 883 887 907 911 919 929 937 941 947
41      953 967 971 977 983 991 997 1009 1013 1019 1021 1031 1033 1039 1049
42      1051 1061 1063 1069 1087 1091 1093 1097 1103 1109 1117 1123 1129 1151
43      1153 1163 1171 1181 1187 1193 1201 1213 1217 1223 1229 1231 1237 1249
44      1259 1277 1279 1283 1289 1291 1297 1301 1303 1307 1319 1321 1327 1361
45      1367 1373 1381 1399 1409 1423 1427 1429 1433 1439 1447 1451 1453 1459
46      1471 1481 1483 1487 1489 1493 1499 1511 1523 1531 1543 1549 1553 1559
47      1567 1571 1579 1583 1597 1601 1607 1609 1613 1619 1621 1627 1637 1657
48      1663 1667 1669 1693 1697 1699 1709 1721 1723 1733 1741 1747 1753 1759
49      1777 1783 1787 1789 1801 1811 1823 1831 1847 1861 1867 1871 1873 1877
50      1879 1889 1901 1907 1913 1931 1933 1949 1951 1973 1979 1987 1993 1997
51      1999 2003 2011 2017 2027 2029 2039 2053 2063 2069 2081 2083 2087 2089
52      2099 2111 2113 2129 2131 2137 2141 2143 2153 2161 2179 2203 2207 2213
53      2221 2237 2239 2243 2251 2267 2269 2273 2281 2287 2293 2297 2309 2311
54      2333 2339 2341 2347 2351 2357 2371 2377 2381 2383 2389 2393 2399 2411
55      2417 2423 2437 2441 2447 2459 2467 2473 2477 2503 2521 2531 2539 2543
56      2549 2551 2557 2579 2591 2593 2609 2617 2621 2633 2647 2657 2659 2663
57      2671 2677 2683 2687 2689 2693 2699 2707 2711 2713 2719 2729 2731 2741
58      2749 2753 2767 2777 2789 2791 2797 2801 2803 2819 2833 2837 2843 2851
59      2857 2861 2879 2887 2897 2903 2909 2917 2927 2939 2953 2957 2963 2969
60      2971 2999 3001 3011 3019 3023 3037 3041 3049 3061 3067 3079 3083 3089
61      3109 3119 3121 3137 3163 3167 3169 3181 3187 3191 3203 3209 3217 3221
62      3229 3251 3253 3257 3259 3271 3299 3301 3307 3313 3319 3323 3329 3331
63      3343 3347 3359 3361 3371 3373 3389 3391 3407 3413 3433 3449 3457 3461
64      3463 3467 3469 3491 3499 3511 3517 3527 3529 3533 3539 3541 3547 3557
65      3559 3571 3581 3583 3593 3607 3613 3617 3623 3631 3637 3643 3659 3671
66      3673 3677 3691 3697 3701 3709 3719 3727 3733 3739 3761 3767 3769 3779
67      3793 3797 3803 3821 3823 3833 3847 3851 3853 3863 3877 3881 3889 3907
68      3911 3917 3919 3923 3929 3931 3943 3947 3967 3989 4001 4003 4007 4013
69      4019 4021 4027 4049 4051 4057 4073 4079 4091 4093 4099 4111 4127 4129
70      4133 4139 4153 4157 4159 4177 4201 4211 4217 4219 4229 4231 4241 4243
71      4253 4259 4261 4271 4273 4283 4289 4297 4327 4337 4339 4349 4357 4363
72      4373 4391 4397 4409 4421 4423 4441 4447 4451 4457 4463 4481 4483 4493
73      4507 4513 4517 4519 4523 4547 4549 4561 4567 4583 4591 4597 4603 4621
74      4637 4639 4643 4649 4651 4657 4663 4673 4679 4691 4703 4721 4723 4729
75      4733 4751 4759 4783 4787 4789 4793 4799 4801 4813 4817 4831 4861 4871
76      4877 4889 4903 4909 4919 4931 4933 4937 4943 4951 4957 4967 4969 4973
77      4987 4993 4999 5003])
78
79 ;; The variable math-prime-factors-finished is set by calcFunc-prfac to
80 ;; indicate whether factoring is complete, and used by calcFunc-factors,
81 ;; calcFunc-totient and calcFunc-moebius.
82 (defvar math-prime-factors-finished)
83
84 ;;; Combinatorics
85
86 (defun calc-gcd (arg)
87   (interactive "P")
88   (calc-slow-wrapper
89    (calc-binary-op "gcd" 'calcFunc-gcd arg)))
90
91 (defun calc-lcm (arg)
92   (interactive "P")
93   (calc-slow-wrapper
94    (calc-binary-op "lcm" 'calcFunc-lcm arg)))
95
96 (defun calc-extended-gcd ()
97   (interactive)
98   (calc-slow-wrapper
99    (calc-enter-result 2 "egcd" (cons 'calcFunc-egcd (calc-top-list-n 2)))))
100
101 (defun calc-factorial (arg)
102   (interactive "P")
103   (calc-slow-wrapper
104    (calc-unary-op "fact" 'calcFunc-fact arg)))
105
106 (defun calc-gamma (arg)
107   (interactive "P")
108   (calc-slow-wrapper
109    (calc-unary-op "gmma" 'calcFunc-gamma arg)))
110
111 (defun calc-double-factorial (arg)
112   (interactive "P")
113   (calc-slow-wrapper
114    (calc-unary-op "dfac" 'calcFunc-dfact arg)))
115
116 (defun calc-choose (arg)
117   (interactive "P")
118   (calc-slow-wrapper
119    (if (calc-is-hyperbolic)
120        (calc-binary-op "perm" 'calcFunc-perm arg)
121      (calc-binary-op "chos" 'calcFunc-choose arg))))
122
123 (defun calc-perm (arg)
124   (interactive "P")
125   (calc-hyperbolic-func)
126   (calc-choose arg))
127
128 (defvar calc-last-random-limit '(float 1 0))
129 (defun calc-random (n)
130   (interactive "P")
131   (calc-slow-wrapper
132    (if n
133        (calc-enter-result 0 "rand" (list 'calcFunc-random
134                                          (calc-get-random-limit
135                                           (prefix-numeric-value n))))
136      (calc-enter-result 1 "rand" (list 'calcFunc-random
137                                        (calc-get-random-limit
138                                         (calc-top-n 1)))))))
139
140 (defun calc-get-random-limit (val)
141   (if (eq val 0)
142       calc-last-random-limit
143     (setq calc-last-random-limit val)))
144
145 (defun calc-rrandom ()
146   (interactive)
147   (calc-slow-wrapper
148    (setq calc-last-random-limit '(float 1 0))
149    (calc-enter-result 0 "rand" (list 'calcFunc-random '(float 1 0)))))
150
151 (defun calc-random-again (arg)
152   (interactive "p")
153   (calc-slow-wrapper
154    (while (>= (setq arg (1- arg)) 0)
155      (calc-enter-result 0 "rand" (list 'calcFunc-random
156                                        calc-last-random-limit)))))
157
158 (defun calc-shuffle (n)
159   (interactive "P")
160   (calc-slow-wrapper
161    (if n
162        (calc-enter-result 1 "shuf" (list 'calcFunc-shuffle
163                                          (prefix-numeric-value n)
164                                          (calc-get-random-limit
165                                           (calc-top-n 1))))
166      (calc-enter-result 2 "shuf" (list 'calcFunc-shuffle
167                                        (calc-top-n 1)
168                                        (calc-get-random-limit
169                                         (calc-top-n 2)))))))
170
171 (defun calc-report-prime-test (res)
172   (cond ((eq res t)
173          (calc-record-message "prim" "Prime (guaranteed)"))
174         ((eq res nil)
175          (calc-record-message "prim" "Non-prime"))
176         (t
177          (calc-record-message
178           "prim" "Probably prime (%d iters; %s%% chance of error)"
179           (nth 1 res)
180           (let ((calc-float-format '(fix 2)))
181             (math-format-number (nth 2 res)))))))
182
183 (defun calc-prime-test (iters)
184   (interactive "P")
185   (calc-slow-wrapper
186    (let* ((n (calc-top-n 1))
187           (res (math-prime-test n iters)))
188      (calc-report-prime-test res))))
189
190 (defvar calc-verbose-nextprime nil)
191
192 (defun calc-next-prime (iters)
193   (interactive "p")
194   (calc-slow-wrapper
195    (let ((calc-verbose-nextprime t))
196      (if (calc-is-inverse)
197          (calc-enter-result 1 "prvp" (list 'calcFunc-prevprime
198                                            (calc-top-n 1) (math-abs iters)))
199        (calc-enter-result 1 "nxtp" (list 'calcFunc-nextprime
200                                          (calc-top-n 1) (math-abs iters)))))))
201
202 (defun calc-prev-prime (iters)
203   (interactive "p")
204   (calc-invert-func)
205   (calc-next-prime iters))
206
207 (defun calc-prime-factors (iters)
208   (interactive "p")
209   (calc-slow-wrapper
210    (let ((res (calcFunc-prfac (calc-top-n 1))))
211      (if (not math-prime-factors-finished)
212          (calc-record-message "pfac" "Warning:  May not be fully factored"))
213      (calc-enter-result 1 "pfac" res))))
214
215 (defun calc-totient (arg)
216   (interactive "P")
217   (calc-slow-wrapper
218    (calc-unary-op "phi" 'calcFunc-totient arg)))
219
220 (defun calc-moebius (arg)
221   (interactive "P")
222   (calc-slow-wrapper
223    (calc-unary-op "mu" 'calcFunc-moebius arg)))
224
225
226 (defun calcFunc-gcd (a b)
227   (if (Math-messy-integerp a)
228       (setq a (math-trunc a)))
229   (if (Math-messy-integerp b)
230       (setq b (math-trunc b)))
231   (cond ((and (Math-integerp a) (Math-integerp b))
232          (math-gcd a b))
233         ((Math-looks-negp a)
234          (calcFunc-gcd (math-neg a) b))
235         ((Math-looks-negp b)
236          (calcFunc-gcd a (math-neg b)))
237         ((Math-zerop a) b)
238         ((Math-zerop b) a)
239         ((and (Math-ratp a)
240               (Math-ratp b))
241          (math-make-frac (math-gcd (if (eq (car-safe a) 'frac) (nth 1 a) a)
242                                    (if (eq (car-safe b) 'frac) (nth 1 b) b))
243                          (calcFunc-lcm
244                           (if (eq (car-safe a) 'frac) (nth 2 a) 1)
245                           (if (eq (car-safe b) 'frac) (nth 2 b) 1))))
246         ((not (Math-integerp a))
247          (calc-record-why 'integerp a)
248          (list 'calcFunc-gcd a b))
249         (t
250          (calc-record-why 'integerp b)
251          (list 'calcFunc-gcd a b))))
252
253 (defun calcFunc-lcm (a b)
254   (if (and (integerp a) (integerp b))
255       (lcm a b)
256     (let ((g (calcFunc-gcd a b)))
257       (if (Math-numberp g)
258           (math-div (math-mul a b) g)
259         (list 'calcFunc-lcm a b)))))
260
261 (defun calcFunc-egcd (a b)   ; Knuth section 4.5.2
262   (cond
263    ((not (Math-integerp a))
264     (if (Math-messy-integerp a)
265         (calcFunc-egcd (math-trunc a) b)
266       (calc-record-why 'integerp a)
267       (list 'calcFunc-egcd a b)))
268    ((not (Math-integerp b))
269     (if (Math-messy-integerp b)
270         (calcFunc-egcd a (math-trunc b))
271       (calc-record-why 'integerp b)
272       (list 'calcFunc-egcd a b)))
273    (t
274     (cons 'vec (xgcd a b)))))
275
276 ;;; Factorial and related functions.
277
278 (defun calcFunc-fact (n)   ; [I I] [F F] [Public]
279   (let (temp)
280     (cond ((Math-integer-negp n)
281            (if calc-infinite-mode
282                '(var uinf var-uinf)
283              (math-reject-arg n 'range)))
284           ((integerp n)
285            (factorial n))
286           ((and (math-messy-integerp n)
287                 (Math-lessp n 100))
288            (math-inexact-result)
289            (setq temp (math-trunc n))
290            (if (>= temp 0)
291                (math-float (calcFunc-fact temp))
292              (math-reject-arg n 'range)))
293           ((math-numberp n)
294            (let* ((q (math-quarter-integer n))
295                   (tn (and q (Math-lessp n 1000) (Math-lessp -1000 n)
296                            (1+ (math-floor n)))))
297              (cond ((and tn (= q 2)
298                          (or calc-symbolic-mode (< (math-abs tn) 20)))
299                     (let ((q (if (< tn 0)
300                                  (math-div
301                                   (math-pow -2 (- tn))
302                                   (math-double-factorial-iter (* -2 tn) 3 1 2))
303                                (math-div
304                                 (math-double-factorial-iter (* 2 tn) 3 1 2)
305                                 (math-pow 2 tn)))))
306                       (math-mul q (if calc-symbolic-mode
307                                       (list 'calcFunc-sqrt '(var pi var-pi))
308                                     (math-sqrt-pi)))))
309                    ((and tn (>= tn 0) (< tn 20)
310                          (memq q '(1 3)))
311                     (math-inexact-result)
312                     (math-div
313                      (math-mul (math-double-factorial-iter (* 4 tn) q 1 4)
314                                (if (= q 1) (math-gamma-1q) (math-gamma-3q)))
315                      (math-pow 4 tn)))
316                    (t
317                     (math-inexact-result)
318                     (math-with-extra-prec 3
319                       (math-gammap1-raw (math-float n)))))))
320           ((equal n '(var inf var-inf)) n)
321           (t (calc-record-why 'numberp n)
322              (list 'calcFunc-fact n)))))
323
324 (math-defcache math-gamma-1q nil
325   (math-with-extra-prec 3
326     (math-gammap1-raw '(float -75 -2))))
327
328 (math-defcache math-gamma-3q nil
329   (math-with-extra-prec 3
330     (math-gammap1-raw '(float -25 -2))))
331
332 (defun math-factorial-iter (count n f)
333   (if (= (% n 5) 1)
334       (math-working (format "factorial(%d)" (1- n)) f))
335   (if (> count 0)
336       (math-factorial-iter (1- count) (1+ n) (math-mul n f))
337     f))
338
339 (defun calcFunc-dfact (n)   ; [I I] [F F] [Public]
340   (cond ((Math-integer-negp n)
341          (if (math-oddp n)
342              (if (eq n -1)
343                  1
344                (math-div (if (eq (math-mod n 4) 3) 1 -1)
345                          (calcFunc-dfact (math-sub -2 n))))
346            (list 'calcFunc-dfact n)))
347         ((Math-zerop n) 1)
348         ((integerp n) (math-double-factorial-iter n (+ 2 (% n 2)) 1 2))
349         ((math-messy-integerp n)
350          (let ((temp (math-trunc n)))
351            (math-inexact-result)
352            (if (natnump temp)
353                (if (Math-lessp temp 200)
354                    (math-with-extra-prec 1
355                      (math-double-factorial-iter temp (+ 2 (% temp 2))
356                                                  '(float 1 0) 2))
357                  (let* ((half (math-div2 temp))
358                         (even (math-mul (math-pow 2 half)
359                                         (calcFunc-fact (math-float half)))))
360                    (if (math-evenp temp)
361                        even
362                      (math-div (calcFunc-fact n) even))))
363              (list 'calcFunc-dfact n))))
364         ((equal n '(var inf var-inf)) n)
365         (t (calc-record-why 'natnump n)
366            (list 'calcFunc-dfact n))))
367
368 (defun math-double-factorial-iter (max n f step)
369   (if (< (% n 12) step)
370       (math-working (format "dfact(%d)" (- n step)) f))
371   (if (<= n max)
372       (math-double-factorial-iter max (+ n step) (math-mul n f) step)
373     f))
374
375 (defun calcFunc-perm (n m)   ; [I I I] [F F F] [Public]
376   (cond ((and (integerp n) (integerp m) (<= m n) (>= m 0))
377          (/ (factorial n) (factorial (- n m))))
378         ((or (not (math-num-integerp n))
379              (not (math-num-integerp m)))
380          (or (math-realp n) (equal n '(var inf var-inf))
381              (math-reject-arg n 'realp))
382          (or (math-realp m) (equal m '(var inf var-inf))
383              (math-reject-arg m 'realp))
384          (and (math-num-integerp n) (math-negp n) (math-reject-arg n 'range))
385          (and (math-num-integerp m) (math-negp m) (math-reject-arg m 'range))
386          (math-div (calcFunc-fact n) (calcFunc-fact (math-sub n m))))
387         (t
388          (let ((tn (math-trunc n))
389                (tm (math-trunc m)))
390            (math-inexact-result)
391            (or (integerp tn) (math-reject-arg tn 'fixnump))
392            (or (integerp tm) (math-reject-arg tm 'fixnump))
393            (or (and (<= tm tn) (>= tm 0)) (math-reject-arg tm 'range))
394            ;; Using SXEmacs factorial seems faster than doing the
395            ;; (smaller) Calc computations.  Also, more accurate.
396            (math-make-float (/ (factorial tn) (factorial (- tn tm))) 0)))))
397
398 (defun calcFunc-choose (n m)   ; [I I I] [F F F] [Public]
399   (cond ((and (integerp n) (integerp m) (<= m n) (>= m 0))
400          (binomial-coefficient n m))
401         ((not (math-realp n))
402          (math-reject-arg n 'realp))
403         ((not (math-realp m))
404          (math-reject-arg m 'realp))
405         ((not (math-num-integerp m))
406          (if (and (math-num-integerp n) (math-negp n))
407              (list 'calcFunc-choose n m)
408            (math-div (calcFunc-fact (math-float n))
409                      (math-mul (calcFunc-fact m)
410                                (calcFunc-fact (math-sub n m))))))
411         ((math-negp m) 0)
412         ((math-negp n)
413          (let ((val (calcFunc-choose (math-add (math-add n m) -1) m)))
414            (if (math-evenp (math-trunc m))
415                val
416              (math-neg val))))
417         ((and (math-num-integerp n)
418               (Math-lessp n m))
419          0)
420         (t
421          (math-inexact-result)
422          (let ((tm (math-trunc m)))
423            (or (integerp tm) (math-reject-arg tm 'fixnump))
424            (if (> tm 100)
425                (math-div (calcFunc-fact (math-float n))
426                          (math-mul (calcFunc-fact (math-float m))
427                                    (calcFunc-fact (math-float
428                                                    (math-sub n m)))))
429              (math-with-extra-prec 1
430                (math-choose-float-iter tm n 1 1)))))))
431
432 (defun math-choose-float-iter (count n i c)
433   (if (= (% i 5) 1)
434       (math-working (format "choose(%d)" (1- i)) c))
435   (if (> count 0)
436       (math-choose-float-iter (1- count) (math-sub n 1) (1+ i)
437                               (math-div (math-mul c n) i))
438     c))
439
440
441 ;;; Stirling numbers.
442
443 (defun calcFunc-stir1 (n m)
444   (math-stirling-number n m 1))
445
446 (defun calcFunc-stir2 (n m)
447   (math-stirling-number n m 0))
448
449 (defvar math-stirling-cache (vector [[1]] [[1]]))
450
451 ;; The variable math-stirling-local-cache is local to
452 ;; math-stirling-number, but is used by math-stirling-1
453 ;; and math-stirling-2, which are called by math-stirling-number.
454 (defvar math-stirling-local-cache)
455
456 (defun math-stirling-number (n m k)
457   (or (math-num-natnump n) (math-reject-arg n 'natnump))
458   (or (math-num-natnump m) (math-reject-arg m 'natnump))
459   (if (consp n) (setq n (math-trunc n)))
460   (or (integerp n) (math-reject-arg n 'fixnump))
461   (if (consp m) (setq m (math-trunc m)))
462   (or (integerp m) (math-reject-arg m 'fixnump))
463   (if (< n m)
464       0
465     (let ((math-stirling-local-cache (aref math-stirling-cache k)))
466       (while (<= (length math-stirling-local-cache) n)
467         (let ((i (1- (length math-stirling-local-cache)))
468               row)
469           (setq math-stirling-local-cache
470                 (vconcat math-stirling-local-cache
471                          (make-vector (length math-stirling-local-cache) nil)))
472           (aset math-stirling-cache k math-stirling-local-cache)
473           (while (< (setq i (1+ i)) (length math-stirling-local-cache))
474             (aset math-stirling-local-cache i (setq row (make-vector (1+ i) nil)))
475             (aset row 0 0)
476             (aset row i 1))))
477       (if (= k 1)
478           (math-stirling-1 n m)
479         (math-stirling-2 n m)))))
480
481 (defun math-stirling-1 (n m)
482   (or (aref (aref math-stirling-local-cache n) m)
483       (aset (aref math-stirling-local-cache n) m
484             (math-add (math-stirling-1 (1- n) (1- m))
485                       (math-mul (- 1 n) (math-stirling-1 (1- n) m))))))
486
487 (defun math-stirling-2 (n m)
488   (or (aref (aref math-stirling-local-cache n) m)
489       (aset (aref math-stirling-local-cache n) m
490             (math-add (math-stirling-2 (1- n) (1- m))
491                       (math-mul m (math-stirling-2 (1- n) m))))))
492
493 (defvar math-random-table nil)
494 (defvar math-last-RandSeed nil)
495 (defvar math-random-ptr1 nil)
496 (defvar math-random-ptr2 nil)
497 (defvar math-random-shift nil)
498
499 ;;; Produce a random 10-bit integer, with (random) if no seed provided,
500 ;;; or else with Numerical Recipes algorithm ran3 / Knuth 3.2.2-A.
501
502 (defvar var-RandSeed)
503 (defvar math-random-cache nil)
504 (defvar math-gaussian-cache nil)
505
506 (defun math-init-random-base ()
507   (if (and (boundp 'var-RandSeed) var-RandSeed)
508       (if (eq (car-safe var-RandSeed) 'vec)
509           nil
510         (if (Math-integerp var-RandSeed)
511             (let* ((seed (math-sub 161803 var-RandSeed))
512                    (mj (1+ (math-mod seed 1000000)))
513                    (mk (1+ (math-mod (math-quotient seed 1000000)
514                                      1000000)))
515                    (i 0))
516               (setq math-random-table (cons 'vec (make-list 55 mj)))
517               (while (<= (setq i (1+ i)) 54)
518                 (let* ((ii (% (* i 21) 55))
519                        (p (nthcdr ii math-random-table)))
520                   (setcar p mk)
521                   (setq mk (- mj mk)
522                         mj (car p)))))
523           (math-reject-arg var-RandSeed "*RandSeed must be an integer"))
524         (setq var-RandSeed (list 'vec var-RandSeed)
525               math-random-ptr1 math-random-table
526               math-random-cache nil
527               math-random-ptr2 (nthcdr 31 math-random-table))
528         (let ((i 200))
529           (while (> (setq i (1- i)) 0)
530             (math-random-base))))
531     (setq var-RandSeed nil
532           math-random-cache nil
533           math-random-shift -4)  ; assume RAND_MAX >= 16383
534     ;; This exercises the random number generator and also helps
535     ;; deduce a better value for RAND_MAX.
536     (let ((i 0))
537       (while (< (setq i (1+ i)) 30)
538         (if (> (lsh (math-abs (random)) math-random-shift) 4095)
539             (setq math-random-shift (1- math-random-shift))))))
540   (setq math-last-RandSeed var-RandSeed
541         math-gaussian-cache nil))
542
543 (defun math-random-base ()
544   (if var-RandSeed
545       (progn
546         (setq math-random-ptr1 (or (cdr math-random-ptr1)
547                                    (cdr math-random-table))
548               math-random-ptr2 (or (cdr math-random-ptr2)
549                                    (cdr math-random-table)))
550         (logand (lsh (setcar math-random-ptr1
551                              (logand (- (car math-random-ptr1)
552                                         (car math-random-ptr2)) 524287))
553                      -6) 1023))
554     (logand (lsh (random) math-random-shift) 1023)))
555
556
557 ;;; Produce a random digit in the range 0..999.
558 ;;; Avoid various pitfalls that may lurk in the built-in (random) function!
559 ;;; Shuffling algorithm from Numerical Recipes, section 7.1.
560 (defvar math-random-last)
561 (defun math-random-three-digit-number ()
562   "Return a random three digit number."
563   (let (i)
564     (or (and (boundp 'var-RandSeed) (eq var-RandSeed math-last-RandSeed))
565         (math-init-random-base))
566     (or math-random-cache
567         (progn
568           (setq math-random-last (math-random-base)
569                 math-random-cache (make-vector 13 nil)
570                 i -1)
571           (while (< (setq i (1+ i)) 13)
572             (aset math-random-cache i (math-random-base)))))
573     (while (progn
574              (setq i (/ math-random-last 79)   ; 0 <= i < 13
575                    math-random-last (aref math-random-cache i))
576              (aset math-random-cache i (math-random-base))
577              (>= math-random-last 1000)))
578     math-random-last))
579
580 ;;; Produce an N-digit random integer.
581 (defun math-random-digits (n)
582   "Produce a random N digit integer."
583   (let* ((slop (% (- 3 (% n 3)) 3))
584          (i (/ (+ n slop) 3))
585          (rnum 0))
586     (while (> i 0)
587       (setq rnum
588             (math-add
589              (math-random-three-digit-number)
590              (math-mul rnum 1000)))
591       (setq i (1- i)))
592     (math-normalize (math-scale-right rnum slop))))
593
594 ;;; Produce a uniformly-distributed random float 0 <= N < 1.
595 (defun math-random-float ()
596   (math-make-float (math-random-digits calc-internal-prec)
597                    (- calc-internal-prec)))
598
599 ;;; Produce a Gaussian-distributed random float with mean=0, sigma=1.
600 (defun math-gaussian-float ()
601   (math-with-extra-prec 2
602     (if (and math-gaussian-cache
603              (= (car math-gaussian-cache) calc-internal-prec))
604         (prog1
605             (cdr math-gaussian-cache)
606           (setq math-gaussian-cache nil))
607       (let* ((v1 (math-add (math-mul (math-random-float) 2) -1))
608              (v2 (math-add (math-mul (math-random-float) 2) -1))
609              (r (math-add (math-sqr v1) (math-sqr v2))))
610         (while (or (not (Math-lessp r 1)) (math-zerop r))
611           (setq v1 (math-add (math-mul (math-random-float) 2) -1)
612                 v2 (math-add (math-mul (math-random-float) 2) -1)
613                 r (math-add (math-sqr v1) (math-sqr v2))))
614         (let ((fac (math-sqrt (math-mul (math-div (calcFunc-ln r) r) -2))))
615           (setq math-gaussian-cache (cons calc-internal-prec
616                                           (math-mul v1 fac)))
617           (math-mul v2 fac))))))
618
619 ;;; Produce a random integer or real 0 <= N < MAX.
620 (defun calcFunc-random (max)
621   (cond ((Math-zerop max)
622          (math-gaussian-float))
623         ((Math-integerp max)
624          (let* ((digs (math-numdigs max))
625                 (r (math-random-digits (+ digs 3))))
626            (math-mod r max)))
627         ((Math-realp max)
628          (math-mul (math-random-float) max))
629         ((and (eq (car max) 'intv) (math-constp max)
630               (Math-lessp (nth 2 max) (nth 3 max)))
631          (if (math-floatp max)
632              (let ((val (math-add (math-mul (math-random-float)
633                                             (math-sub (nth 3 max) (nth 2 max)))
634                                   (nth 2 max))))
635                (if (or (and (memq (nth 1 max) '(0 1))      ; almost not worth
636                             (Math-equal val (nth 2 max)))  ;   checking!
637                        (and (memq (nth 1 max) '(0 2))
638                             (Math-equal val (nth 3 max))))
639                    (calcFunc-random max)
640                  val))
641            (let ((lo (if (memq (nth 1 max) '(0 1))
642                          (math-add (nth 2 max) 1) (nth 2 max)))
643                  (hi (if (memq (nth 1 max) '(1 3))
644                          (math-add (nth 3 max) 1) (nth 3 max))))
645              (if (Math-lessp lo hi)
646                  (math-add (calcFunc-random (math-sub hi lo)) lo)
647                (math-reject-arg max "*Empty interval")))))
648         ((eq (car max) 'vec)
649          (if (cdr max)
650              (nth (1+ (calcFunc-random (1- (length max)))) max)
651            (math-reject-arg max "*Empty list")))
652         ((and (eq (car max) 'sdev) (math-constp max) (Math-realp (nth 1 max)))
653          (math-add (math-mul (math-gaussian-float) (nth 2 max)) (nth 1 max)))
654         (t (math-reject-arg max 'realp))))
655
656 ;;; Choose N objects at random from the set MAX without duplicates.
657 (defun calcFunc-shuffle (n &optional max)
658   (or max (setq max n n -1))
659   (or (and (Math-num-integerp n)
660            (or (natnump (setq n (math-trunc n))) (eq n -1)))
661       (math-reject-arg n 'integerp))
662   (cond ((or (math-zerop max)
663              (math-floatp max)
664              (eq (car-safe max) 'sdev))
665          (if (< n 0)
666              (math-reject-arg n 'natnump)
667            (math-simple-shuffle n max)))
668         ((and (<= n 1) (>= n 0))
669          (math-simple-shuffle n max))
670         ((and (eq (car-safe max) 'intv) (math-constp max))
671          (let ((num (math-add (math-sub (nth 3 max) (nth 2 max))
672                               (cdr (assq (nth 1 max)
673                                          '((0 . -1) (1 . 0)
674                                            (2 . 0) (3 . 1))))))
675                (min (math-add (nth 2 max) (if (memq (nth 1 max) '(0 1))
676                                               1 0))))
677            (if (< n 0) (setq n num))
678            (or (math-posp num) (math-reject-arg max 'range))
679            (and (Math-lessp num n) (math-reject-arg n 'range))
680            (if (Math-lessp n (math-quotient num 3))
681                (math-simple-shuffle n max)
682              (if (> (* n 4) (* num 3))
683                  (math-add (math-sub min 1)
684                            (math-shuffle-list n num (calcFunc-index num)))
685                (let ((tot 0)
686                      (m 0)
687                      (vec nil))
688                  (while (< m n)
689                    (if (< (calcFunc-random (- num tot)) (- n m))
690                        (setq vec (cons (math-add min tot) vec)
691                              m (1+ m)))
692                    (setq tot (1+ tot)))
693                  (math-shuffle-list n n (cons 'vec vec)))))))
694         ((eq (car-safe max) 'vec)
695          (let ((size (1- (length max))))
696            (if (< n 0) (setq n size))
697            (if (and (> n (/ size 2)) (<= n size))
698                (math-shuffle-list n size (copy-sequence max))
699              (let* ((vals (calcFunc-shuffle
700                            n (list 'intv 3 1 (1- (length max)))))
701                     (p vals))
702                (while (setq p (cdr p))
703                  (setcar p (nth (car p) max)))
704                vals))))
705         ((math-integerp max)
706          (if (math-posp max)
707              (calcFunc-shuffle n (list 'intv 2 0 max))
708            (calcFunc-shuffle n (list 'intv 1 max 0))))
709         (t (math-reject-arg max 'realp))))
710
711 (defun math-simple-shuffle (n max)
712   (let ((vec nil)
713         val)
714     (while (>= (setq n (1- n)) 0)
715       (while (math-member (setq val (calcFunc-random max)) vec))
716       (setq vec (cons val vec)))
717     (cons 'vec vec)))
718
719 (defun math-shuffle-list (n size vec)
720   (let ((j size)
721         k temp
722         (p vec))
723     (while (cdr (setq p (cdr p)))
724       (setq k (calcFunc-random j)
725             j (1- j)
726             temp (nth k p))
727       (setcar (nthcdr k p) (car p))
728       (setcar p temp))
729     (cons 'vec (nthcdr (- size n -1) vec))))
730
731 (defun math-member (x list)
732   (while (and list (not (equal x (car list))))
733     (setq list (cdr list)))
734   list)
735
736 ;;; Check if the integer N is prime.  [X I]
737 ;;; Return nil if non-prime,
738 ;;;        t if prime,
739 ;;;        ('probably-prime iters prob) if probably prime.
740 (defun math-prime-test (n iters)
741   (if (and (Math-vectorp n) (cdr n))
742       (setq n (nth (1- (length n)) n)))
743   (if (Math-messy-integerp n)
744       (setq n (math-trunc n)))
745   (cond ((not (Math-integerp n))
746          (error "Argument must be an integer"))
747         ((Math-integer-negp n)
748          nil)
749         (t
750          (let ((res (primep n iters)))
751            (if (eq res 'probably-prime)
752                (progn
753                  (unless iters (setq iters 8))
754                  (list 'probabily-prime iters (math-pow '(float 25 -2) iters)))
755              res)))))
756
757 (defun calcFunc-prime (n &optional iters)
758   (or (math-num-integerp n) (math-reject-arg n 'integerp))
759   (or (not iters) (math-num-integerp iters) (math-reject-arg iters 'integerp))
760   (if (math-prime-test (math-trunc n) iters)
761       1
762     0))
763
764 ;;; Theory: summing base-10^6 digits modulo 111111 is "casting out 999999s".
765 ;;; Initial probability that N is prime is 1/ln(N) = log10(e)/log10(N).
766 ;;; After culling [2,3,5,7,11,13,37], probability of primality is 5.36 x more.
767 ;;; Initial reported probability of non-primality is thus 100% - this.
768 ;;; Each Fermat step multiplies this probability by 25%.
769 ;;; The Fermat step is algorithm P from Knuth section 4.5.4.
770
771
772 (defun calcFunc-prfac (n)
773   (setq math-prime-factors-finished t)
774   (if (Math-messy-integerp n)
775       (setq n (math-trunc n)))
776   (if (Math-natnump n)
777       (if (Math-natnum-lessp 2 n)
778           (let (factors res p (i 0))
779             (while (and (not (eq n 1))
780                         (< i (length math-primes-table)))
781               (setq p (aref math-primes-table i))
782               (while (eq (cdr (setq res (cond ((eq n p) (cons 1 0))
783                                               ((eq n 1) (cons 0 1))
784                                               ((consp n) (math-idivmod n p))
785                                               (t (cons (/ n p) (% n p))))))
786                          0)
787                 (math-working "factor" p)
788                 (setq factors (nconc factors (list p))
789                       n (car res)))
790               (or (eq n 1)
791                   (Math-natnum-lessp p (car res))
792                   (setq factors (nconc factors (list n))
793                         n 1))
794               (setq i (1+ i)))
795             (or (setq math-prime-factors-finished (eq n 1))
796                 (setq factors (nconc factors (list n))))
797             (cons 'vec factors))
798         (list 'vec n))
799     (if (Math-integerp n)
800         (if (eq n -1)
801             (list 'vec n)
802           (cons 'vec (cons -1 (cdr (calcFunc-prfac (math-neg n))))))
803       (calc-record-why 'integerp n)
804       (list 'calcFunc-prfac n))))
805
806 (defun calcFunc-totient (n)
807   (if (Math-messy-integerp n)
808       (setq n (math-trunc n)))
809   (if (Math-natnump n)
810       (if (Math-natnum-lessp n 2)
811           (if (Math-negp n)
812               (calcFunc-totient (math-abs n))
813             n)
814         (let ((factors (cdr (calcFunc-prfac n)))
815               p)
816           (if math-prime-factors-finished
817               (progn
818                 (while factors
819                   (setq p (car factors)
820                         n (math-mul (math-div n p) (math-add p -1)))
821                   (while (equal p (car factors))
822                     (setq factors (cdr factors))))
823                 n)
824             (calc-record-why "*Number too big to factor" n)
825             (list 'calcFunc-totient n))))
826     (calc-record-why 'natnump n)
827     (list 'calcFunc-totient n)))
828
829 (defun calcFunc-moebius (n)
830   (if (Math-messy-integerp n)
831       (setq n (math-trunc n)))
832   (if (and (Math-natnump n) (not (eq n 0)))
833       (if (Math-natnum-lessp n 2)
834           (if (Math-negp n)
835               (calcFunc-moebius (math-abs n))
836             1)
837         (let ((factors (cdr (calcFunc-prfac n)))
838               (mu 1))
839           (if math-prime-factors-finished
840               (progn
841                 (while factors
842                   (setq mu (if (equal (car factors) (nth 1 factors))
843                                0 (math-neg mu))
844                         factors (cdr factors)))
845                 mu)
846             (calc-record-why "Number too big to factor" n)
847             (list 'calcFunc-moebius n))))
848     (calc-record-why 'posintp n)
849     (list 'calcFunc-moebius n)))
850
851
852 (defun calcFunc-nextprime (n &optional iters)
853   (if (Math-integerp n)
854       (if (Math-integer-negp n)
855           2
856         (next-prime n))))
857
858 (defun calcFunc-prevprime (n &optional iters)
859   (if (Math-integerp n)
860       (if (Math-lessp n 4)
861           2
862         (if (math-evenp n)
863             (setq n (math-add n 1)))
864         (while (not (math-prime-test
865                      (setq n (math-add n -2))
866                      iters)))
867         n)
868     (if (Math-realp n)
869         (calcFunc-prevprime (math-ceiling n) iters)
870       (math-reject-arg n 'integerp))))
871
872 (provide 'calc-comb)
873
874 ;;; calc-comb.el ends here