1 ;;; calcalg3.el --- more algebraic functions for Calc
3 ;; Copyright (C) 1990, 1991, 1992, 1993, 2001 Free Software Foundation, Inc.
5 ;; Author: David Gillespie <daveg@synaptics.com>
6 ;; Maintainer: Colin Walters <walters@debian.org>
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is distributed in the hope that it will be useful,
11 ;; but WITHOUT ANY WARRANTY. No author or distributor
12 ;; accepts responsibility to anyone for the consequences of using it
13 ;; or for whether it serves any particular purpose or works at all,
14 ;; unless he says so in writing. Refer to the GNU Emacs General Public
15 ;; License for full details.
17 ;; Everyone is granted permission to copy, modify and redistribute
18 ;; GNU Emacs, but only under the conditions described in the
19 ;; GNU Emacs General Public License. A copy of this license is
20 ;; supposed to have been given to you along with GNU Emacs so you
21 ;; can know your rights and responsibilities. It should be in a
22 ;; file named COPYING. Among other things, the copyright notice
23 ;; and this notice must be preserved on all copies.
29 ;; This file is autoloaded from calc-ext.el.
34 (defun calc-Need-calc-alg-3 () nil
)
37 (defun calc-find-root (var)
38 (interactive "sVariable(s) to solve for: ")
40 (let ((func (if (calc-is-hyperbolic) 'calcFunc-wroot
'calcFunc-root
)))
41 (if (or (equal var
"") (equal var
"$"))
42 (calc-enter-result 2 "root" (list func
46 (let ((var (if (and (string-match ",\\|[^ ] +[^ ]" var
)
47 (not (string-match "\\[" var
)))
48 (math-read-expr (concat "[" var
"]"))
49 (math-read-expr var
))))
50 (if (eq (car-safe var
) 'error
)
51 (error "Bad format in expression: %s" (nth 1 var
)))
52 (calc-enter-result 1 "root" (list func
57 (defun calc-find-minimum (var)
58 (interactive "sVariable(s) to minimize over: ")
60 (let ((func (if (calc-is-inverse)
61 (if (calc-is-hyperbolic)
62 'calcFunc-wmaximize
'calcFunc-maximize
)
63 (if (calc-is-hyperbolic)
64 'calcFunc-wminimize
'calcFunc-minimize
)))
65 (tag (if (calc-is-inverse) "max" "min")))
66 (if (or (equal var
"") (equal var
"$"))
67 (calc-enter-result 2 tag
(list func
71 (let ((var (if (and (string-match ",\\|[^ ] +[^ ]" var
)
72 (not (string-match "\\[" var
)))
73 (math-read-expr (concat "[" var
"]"))
74 (math-read-expr var
))))
75 (if (eq (car-safe var
) 'error
)
76 (error "Bad format in expression: %s" (nth 1 var
)))
77 (calc-enter-result 1 tag
(list func
82 (defun calc-find-maximum (var)
83 (interactive "sVariable to maximize over: ")
85 (calc-find-minimum var
))
88 (defun calc-poly-interp (arg)
91 (let ((data (calc-top 2)))
92 (if (or (consp arg
) (eq arg
0) (eq arg
2))
93 (setq data
(cons 'vec
(calc-top-list 2 2)))
95 (error "Bad prefix argument")))
96 (if (calc-is-hyperbolic)
97 (calc-enter-result 1 "rati" (list 'calcFunc-ratint data
(calc-top 1)))
98 (calc-enter-result 1 "poli" (list 'calcFunc-polint data
102 (defun calc-curve-fit (arg &optional model coefnames varnames
)
105 (setq calc-aborted-prefix nil
)
106 (let ((func (if (calc-is-inverse) 'calcFunc-xfit
107 (if (calc-is-hyperbolic) 'calcFunc-efit
112 (msgs '( "(Press ? for help)"
113 "1 = linear or multilinear"
114 "2-9 = polynomial fits; i = interpolating polynomial"
115 "p = a x^b, ^ = a b^x"
116 "e = a exp(b x), x = exp(a + b x), l = a + b ln(x)"
117 "E = a 10^(b x), X = 10^(a + b x), L = a + b log10(x)"
119 "g = (a/b sqrt(2 pi)) exp(-0.5*((x-c)/b)^2)"
120 "h prefix = homogeneous model (no constant term)"
121 "' = alg entry, $ = stack, u = Model1, U = Model2")))
123 (message "Fit to model: %s:%s"
126 (setq key
(read-char))
130 (setq which
(%
(1+ which
) (length msgs
))))
132 (setq homog
(not homog
)))
140 ((or (consp arg
) (eq arg
0))
143 data
(if (math-matrixp data
)
144 (append data
(list (calc-top (1- n
))))
145 (list 'vec data
(calc-top (1- n
))))))
146 ((> (setq arg
(prefix-numeric-value arg
)) 0)
147 (setq data
(cons 'vec
(calc-top-list arg
(1+ n
)))
149 (t (error "Bad prefix argument")))
150 (or (math-matrixp data
) (not (cdr (cdr data
)))
151 (error "Data matrix is not a matrix!"))
152 (setq nvars
(- (length data
) 2)
156 ((= key ?
1) ; linear or multilinear
157 (calc-get-fit-variables nvars
(1+ nvars
) (and homog
0))
158 (setq model
(math-mul coefnames
159 (cons 'vec
(cons 1 (cdr varnames
))))))
160 ((and (>= key ?
2) (<= key ?
9)) ; polynomial
161 (calc-get-fit-variables 1 (- key ?
0 -
1) (and homog
0))
162 (setq model
(math-build-polynomial-expr (cdr coefnames
)
164 ((= key ?i
) ; exact polynomial
165 (calc-get-fit-variables 1 (1- (length (nth 1 data
)))
167 (setq model
(math-build-polynomial-expr (cdr coefnames
)
169 ((= key ?p
) ; power law
170 (calc-get-fit-variables nvars
(1+ nvars
) (and homog
1))
171 (setq model
(math-mul (nth 1 coefnames
)
177 (cons 'vec
(cdr (cdr coefnames
))))))))
178 ((= key ?^
) ; exponential law
179 (calc-get-fit-variables nvars
(1+ nvars
) (and homog
1))
180 (setq model
(math-mul (nth 1 coefnames
)
185 (cons 'vec
(cdr (cdr coefnames
)))
188 (calc-get-fit-variables nvars
(1+ nvars
) (and homog
1))
189 (setq model
(math-mul (nth 1 coefnames
)
197 (^
10 (var a var-a
))))
200 (cons 'vec
(cdr (cdr coefnames
)))
203 (calc-get-fit-variables nvars
(1+ nvars
) (and homog
0))
204 (setq model
(math-mul coefnames
205 (cons 'vec
(cons 1 (cdr varnames
)))))
206 (setq model
(if (eq key ?x
)
207 (list 'calcFunc-exp model
)
208 (list '^
10 model
))))
210 (calc-get-fit-variables nvars
(1+ nvars
) (and homog
0))
211 (setq model
(math-mul coefnames
213 (cons 1 (cdr (calcFunc-map
220 (calc-get-fit-variables nvars
(1+ (* 2 nvars
)) (and homog
0))
223 (setq model
(nth 1 c
))
224 (while (setq v
(cdr v
) c
(cdr (cdr c
)))
225 (setq model
(math-add
230 (list '-
(car v
) (nth 1 c
))
233 (setq model
(math-read-expr "(AFit / BFit sqrt(2 pi)) exp(-0.5 * ((XFit - CFit) / BFit)^2)")
234 varnames
'(vec (var XFit var-XFit
))
235 coefnames
'(vec (var AFit var-AFit
)
237 (var CFit var-CFit
)))
238 (calc-get-fit-variables 1 (1- (length coefnames
)) (and homog
1)))
239 ((memq key
'(?\$ ?
\' ?u ?U
))
243 (let* ((calc-dollar-values calc-arg-values
)
245 (calc-hashes-used 0))
246 (setq model
(calc-do-alg-entry "" "Model formula: "))
247 (if (/= (length model
) 1)
248 (error "Bad format"))
249 (setq model
(car model
)
251 (if (> calc-dollar-used
0)
254 (nthcdr (- (length calc-arg-values
)
256 (reverse calc-arg-values
))))
257 (if (> calc-hashes-used
0)
259 (cons 'vec
(calc-invent-args
260 calc-hashes-used
))))))
262 (setq model
(cond ((eq key ?u
)
263 (calc-var-value 'var-Model1
))
265 (calc-var-value 'var-Model2
))
267 (or model
(error "User model not yet defined"))
268 (if (math-vectorp model
)
269 (if (and (memq (length model
) '(3 4))
270 (not (math-objvecp (nth 1 model
)))
271 (math-vectorp (nth 2 model
))
272 (or (null (nth 3 model
))
273 (math-vectorp (nth 3 model
))))
274 (setq varnames
(nth 2 model
)
275 coefnames
(or (nth 3 model
)
280 (error "Incorrect model specifier")))))
282 (let ((with-y (eq (car-safe model
) 'calcFunc-eq
)))
284 (calc-get-fit-variables (if with-y
(1+ nvars
) nvars
)
285 (1- (length coefnames
))
289 (let* ((coefs (math-all-vars-but model nil
))
291 (n (- (length coefs
) nvars
(if with-y
2 1)))
294 (error "Not enough variables in model"))
295 (setq p
(nthcdr n coefs
))
298 (calc-get-fit-variables (if with-y
(1+ nvars
) nvars
)
300 vars coefs with-y
)))))
302 (calc-record (list 'vec model varnames coefnames
)
305 (let ((calc-fit-to-trail t
))
306 (calc-enter-result n
(substring (symbol-name func
) 9)
308 (if (= (length varnames
) 2)
311 (if (= (length coefnames
) 2)
315 (if (consp calc-fit-to-trail
)
316 (calc-record (calc-normalize calc-fit-to-trail
) "parm"))))))
318 (defun calc-invent-independent-variables (n &optional but
)
319 (calc-invent-variables n but
'(x y z t
) "x"))
321 (defun calc-invent-parameter-variables (n &optional but
)
322 (calc-invent-variables n but
'(a b c d
) "a"))
324 (defun calc-invent-variables (num but names base
)
328 (while (and (> n
0) names
)
329 (setq var
(math-build-var-name (if (consp names
)
331 (concat base
(int-to-string
332 (setq nn
(1+ nn
)))))))
333 (or (math-expr-contains (cons 'vec but
) var
)
334 (setq vars
(cons var vars
)
336 (or (symbolp names
) (setq names
(cdr names
))))
339 (calc-invent-variables num but t base
))))
341 (defun calc-get-fit-variables (nv nc
&optional defv defc with-y homog
)
342 (or (= nv
(if with-y
(1+ nvars
) nvars
))
343 (error "Wrong number of data vectors for this type of model"))
350 (setq defv
(calc-invent-independent-variables nv
)))
352 (setq defc
(calc-invent-parameter-variables nc defv
)))
353 (let ((vars (read-string (format "Fitting variables: (default %s; %s) "
354 (mapconcat 'symbol-name
355 (mapcar (function (lambda (v)
359 (mapconcat 'symbol-name
360 (mapcar (function (lambda (v)
365 (setq vars
(if (string-match "\\[" vars
)
366 (math-read-expr vars
)
367 (math-read-expr (concat "[" vars
"]"))))
368 (if (eq (car-safe vars
) 'error
)
369 (error "Bad format in expression: %s" (nth 2 vars
)))
370 (or (math-vectorp vars
)
371 (error "Expected a variable or vector of variables"))
372 (if (equal vars
'(vec))
373 (setq vars
(cons 'vec defv
)
374 coefs
(cons 'vec defc
))
375 (if (math-vectorp (nth 1 vars
))
376 (if (and (= (length vars
) 3)
377 (math-vectorp (nth 2 vars
)))
378 (setq coefs
(nth 2 vars
)
381 "Expected independent variables vector, then parameters vector"))
382 (setq coefs
(cons 'vec defc
))))
383 (or (= nv
(1- (length vars
)))
384 (and (not with-y
) (= (1+ nv
) (1- (length vars
))))
385 (error "Expected %d independent variable%s" nv
(if (= nv
1) "" "s")))
386 (or (= nc
(1- (length coefs
)))
387 (error "Expected %d parameter variable%s" nc
(if (= nc
1) "" "s")))
389 (setq coefs
(cons 'vec
(cons homog
(cdr coefs
)))))
391 (setq model
(math-multi-subst model
(cdr varnames
) (cdr vars
))))
393 (setq model
(math-multi-subst model
(cdr coefnames
) (cdr coefs
))))
400 ;;; The following algorithms are from Numerical Recipes chapter 9.
402 ;;; "rtnewt" with safety kludges
403 (defun math-newton-root (expr deriv guess orig-guess limit
)
404 (math-working "newton" guess
)
405 (let* ((var-DUMMY guess
)
407 (setq next
(math-evaluate-expr expr
)
408 dval
(math-evaluate-expr deriv
))
409 (if (and (Math-numberp next
)
411 (not (Math-zerop dval
)))
413 (setq next
(math-sub guess
(math-div next dval
)))
414 (if (math-nearly-equal guess
(setq next
(math-float next
)))
416 (setq var-DUMMY next
)
417 (list 'vec next
(math-evaluate-expr expr
)))
418 (if (Math-lessp (math-abs-approx (math-sub next orig-guess
))
420 (math-newton-root expr deriv next orig-guess limit
)
421 (math-reject-arg next
"*Newton's method failed to converge"))))
422 (math-reject-arg next
"*Newton's method encountered a singularity"))))
424 ;;; Inspired by "rtsafe"
425 (defun math-newton-search-root (expr deriv guess vguess ostep oostep
427 (let ((var-DUMMY guess
)
431 (math-working "newton" (list 'intv
0 low high
))
432 (math-working "bisect" (list 'intv
0 low high
))
433 (setq ostep
(math-mul-float (math-sub-float high low
)
435 guess
(math-add-float low ostep
)
437 vguess
(math-evaluate-expr expr
))
438 (or (Math-realp vguess
)
440 (setq ostep
(math-mul-float ostep
'(float 6 -
1))
441 guess
(math-add-float low ostep
)
443 vguess
(math-evaluate-expr expr
))
444 (or (math-realp vguess
)
446 (setq ostep
(math-mul-float ostep
'(float 123456 -
5))
447 guess
(math-add-float low ostep
)
451 (setq vguess
(math-evaluate-expr expr
)))
452 (or (Math-realp vguess
)
453 (math-reject-arg guess
"*Newton's method encountered a singularity"))
454 (setq vguess
(math-float vguess
))
455 (if (eq (Math-negp vlow
) (setq pos
(Math-posp vguess
)))
458 (if (eq (Math-negp vhigh
) pos
)
462 (if (or (Math-zerop vguess
)
463 (math-nearly-equal low high
))
464 (list 'vec guess vguess
)
465 (setq step
(math-evaluate-expr deriv
))
466 (if (and (Math-realp step
)
467 (not (Math-zerop step
))
468 (setq step
(math-div-float vguess
(math-float step
))
469 next
(math-sub-float guess step
))
470 (not (math-lessp-float high next
))
471 (not (math-lessp-float next low
)))
474 vnext
(math-evaluate-expr expr
))
475 (if (or (Math-zerop vnext
)
476 (math-nearly-equal next guess
))
477 (list 'vec next vnext
)
479 (math-lessp-float (math-abs (or oostep
483 (math-mul-float '(float 2 0)
485 (math-newton-search-root expr deriv nil nil nil ostep
487 (math-newton-search-root expr deriv next vnext step ostep
488 low vlow high vhigh
))))
489 (if (or (and (Math-posp vlow
) (Math-posp vhigh
))
490 (and (Math-negp vlow
) (Math-negp vhigh
)))
491 (math-search-root expr deriv low vlow high vhigh
)
492 (math-newton-search-root expr deriv nil nil nil ostep
493 low vlow high vhigh
))))))
495 ;;; Search for a root in an interval with no overt zero crossing.
496 (defun math-search-root (expr deriv low vlow high vhigh
)
500 (iterlim (if (eq root-widen
'point
)
501 (+ calc-internal-prec
10)
503 (factor (if (eq root-widen
'point
)
506 (prev nil
) vprev waslow
508 (while (or (and (math-posp vlow
) (math-posp vhigh
))
509 (and (math-negp vlow
) (math-negp vhigh
)))
510 (math-working "widen" (list 'intv
0 low high
))
511 (if (> (setq iters
(1+ iters
)) iterlim
)
512 (math-reject-arg (list 'intv
0 low high
)
513 "*Unable to bracket root"))
514 (if (= iters calc-internal-prec
)
515 (setq factor
'(float 16 -
1)))
516 (setq diff
(math-mul-float (math-sub-float high low
) factor
))
517 (if (Math-zerop diff
)
518 (setq high
(calcFunc-incr high
10))
519 (if (math-lessp-float (math-abs vlow
) (math-abs vhigh
))
522 low
(math-sub low diff
)
525 vlow
(math-evaluate-expr expr
))
528 high
(math-add high diff
)
531 vhigh
(math-evaluate-expr expr
)))))
534 (setq high prev vhigh vprev
)
535 (setq low prev vlow vprev
)))
537 (or (Math-realp vlow
)
538 (math-reject-arg vlow
'realp
))
539 (or (Math-realp vhigh
)
540 (math-reject-arg vhigh
'realp
))
541 (let ((xvals (list low high
))
542 (yvals (list vlow vhigh
))
543 (pos (Math-posp vlow
))
545 (step (math-sub-float high low
))
547 (while (and (<= (setq levels
(1+ levels
)) 5)
551 step
(math-mul-float step
'(float 497 -
3)))
552 (while (and (cdr xp
) (not found
))
553 (if (Math-realp (car yp
))
556 (setq high
(math-add-float (car xp
) step
)
558 vhigh
(math-evaluate-expr expr
))
559 (math-working "search" high
)
560 (if (and (Math-realp vhigh
)
561 (eq (math-negp vhigh
) pos
))
563 (setcdr xp
(cons high
(cdr xp
)))
564 (setcdr yp
(cons vhigh
(cdr yp
)))
565 (setq xp
(cdr (cdr xp
))
566 yp
(cdr (cdr yp
))))))))
568 (if (Math-zerop vhigh
)
569 (list 'vec high vhigh
)
570 (if (Math-zerop vlow
)
573 (math-newton-search-root expr deriv nil nil nil nil
575 (math-bisect-root expr low vlow high vhigh
))))
576 (math-reject-arg (list 'intv
3 low high
)
577 "*Unable to find a sign change in this interval"))))
579 ;;; "rtbis" (but we should be using Brent's method)
580 (defun math-bisect-root (expr low vlow high vhigh
)
581 (let ((step (math-sub-float high low
))
582 (pos (Math-posp vhigh
))
585 (while (not (or (math-nearly-equal low
586 (setq step
(math-mul-float
588 mid
(math-add-float low step
)))
591 vmid
(math-evaluate-expr expr
))
593 (math-working "bisect" mid
)
594 (if (eq (Math-posp vmid
) pos
)
599 (list 'vec mid vmid
)))
602 (defun math-newton-multi (expr jacob n guess orig-guess limit
)
605 p2 expr-val jacob-val next
)
606 (while (< (setq p
(cdr p
) m
(1+ m
)) n
)
607 (set (nth 2 (aref math-root-vars m
)) (car p
)))
608 (setq expr-val
(math-evaluate-expr expr
)
609 jacob-val
(math-evaluate-expr jacob
))
610 (unless (and (math-constp expr-val
)
611 (math-constp jacob-val
))
612 (math-reject-arg guess
"*Newton's method encountered a singularity"))
613 (setq next
(math-add guess
(math-div (math-float (math-neg expr-val
))
614 (math-float jacob-val
)))
616 (math-working "newton" next
)
617 (while (and (setq p
(cdr p
) p2
(cdr p2
))
618 (math-nearly-equal (car p
) (car p2
))))
620 (if (Math-lessp (math-abs-approx (math-sub next orig-guess
))
622 (math-newton-multi expr jacob n next orig-guess limit
)
623 (math-reject-arg nil
"*Newton's method failed to converge"))
624 (list 'vec next expr-val
))))
626 (defvar math-root-vars
[(var DUMMY var-DUMMY
)])
628 (defun math-find-root (expr var guess root-widen
)
629 (if (eq (car-safe expr
) 'vec
)
630 (let ((n (1- (length expr
)))
631 (calc-symbolic-mode nil
)
635 (unless (eq (car-safe var
) 'vec
)
636 (math-reject-arg var
'vectorp
))
637 (unless (= (length var
) (1+ n
))
638 (math-dimension-error))
639 (setq expr
(copy-sequence expr
))
640 (while (>= n
(length math-root-vars
))
641 (let ((symb (intern (concat "math-root-v"
643 (length math-root-vars
))))))
644 (setq math-root-vars
(vconcat math-root-vars
645 (vector (list 'var symb symb
))))))
647 (while (< (setq m
(1+ m
)) n
)
648 (set (nth 2 (aref math-root-vars m
)) nil
))
650 (while (setq m
(1+ m
) p
(cdr p
))
651 (or (eq (car-safe (car p
)) 'var
)
652 (math-reject-arg var
"*Expected a variable"))
654 (while (setq p2
(cdr p2
))
655 (setcar p2
(math-expr-subst (car p2
) (car p
)
656 (aref math-root-vars m
)))))
657 (unless (eq (car-safe guess
) 'vec
)
658 (math-reject-arg guess
'vectorp
))
659 (unless (= (length guess
) (1+ n
))
660 (math-dimension-error))
661 (setq guess
(copy-sequence guess
)
663 (while (setq p
(cdr p
))
664 (or (Math-numberp (car guess
))
665 (math-reject-arg guess
'numberp
))
666 (setcar p
(math-float (car p
))))
668 (while (setq p
(cdr p
))
669 (if (assq (car-safe (car p
)) calc-tweak-eqn-table
)
670 (setcar p
(math-sub (nth 1 (car p
)) (nth 2 (car p
)))))
671 (setcar p
(math-evaluate-expr (car p
)))
672 (setq row
(list 'vec
)
674 (while (< (setq m
(1+ m
)) n
)
675 (nconc row
(list (math-evaluate-expr
676 (or (calcFunc-deriv (car p
)
677 (aref math-root-vars m
)
681 "*Formulas must be differentiable"))))))
682 (nconc jacob
(list row
)))
683 (setq m
(math-abs-approx guess
))
684 (math-newton-multi expr jacob n guess guess
685 (if (math-zerop m
) '(float 1 3) (math-mul m
10))))
686 (unless (eq (car-safe var
) 'var
)
687 (math-reject-arg var
"*Expected a variable"))
688 (unless (math-expr-contains expr var
)
689 (math-reject-arg expr
"*Formula does not contain specified variable"))
690 (if (assq (car expr
) calc-tweak-eqn-table
)
691 (setq expr
(math-sub (nth 1 expr
) (nth 2 expr
))))
692 (math-with-extra-prec 2
693 (setq expr
(math-expr-subst expr var
'(var DUMMY var-DUMMY
)))
694 (let* ((calc-symbolic-mode nil
)
696 (expr (math-evaluate-expr expr
))
697 (deriv (calcFunc-deriv expr
'(var DUMMY var-DUMMY
) nil t
))
699 (and deriv
(setq deriv
(math-evaluate-expr deriv
)))
700 (setq guess
(math-float guess
))
701 (if (and (math-numberp guess
)
703 (math-newton-root expr deriv guess guess
704 (if (math-zerop guess
) '(float 1 6)
705 (math-mul (math-abs-approx guess
) 100)))
706 (if (Math-realp guess
)
710 vlow
(math-evaluate-expr expr
)
713 (if (eq (car guess
) 'intv
)
715 (or (math-constp guess
) (math-reject-arg guess
'constp
))
716 (setq low
(nth 2 guess
)
718 (if (memq (nth 1 guess
) '(0 1))
719 (setq low
(calcFunc-incr low
1 high
)))
720 (if (memq (nth 1 guess
) '(0 2))
721 (setq high
(calcFunc-incr high -
1 low
)))
723 vlow
(math-evaluate-expr expr
)
725 vhigh
(math-evaluate-expr expr
)))
726 (if (math-complexp guess
)
727 (math-reject-arg "*Complex root finder must have derivative")
728 (math-reject-arg guess
'realp
))))
729 (if (Math-zerop vlow
)
731 (if (Math-zerop vhigh
)
732 (list 'vec high vhigh
)
733 (if (and deriv
(Math-numberp vlow
) (Math-numberp vhigh
))
734 (math-newton-search-root expr deriv nil nil nil nil
736 (if (or (and (Math-posp vlow
) (Math-posp vhigh
))
737 (and (Math-negp vlow
) (Math-negp vhigh
))
738 (not (Math-numberp vlow
))
739 (not (Math-numberp vhigh
)))
740 (math-search-root expr deriv low vlow high vhigh
)
741 (math-bisect-root expr low vlow high vhigh
))))))))))
743 (defun calcFunc-root (expr var guess
)
744 (math-find-root expr var guess nil
))
746 (defun calcFunc-wroot (expr var guess
)
747 (math-find-root expr var guess t
))
752 ;;; The following algorithms come from Numerical Recipes, chapter 10.
754 (defun math-min-eval (expr a
)
757 (while (setq m
(1+ m
) a
(cdr a
))
758 (set (nth 2 (aref math-min-vars m
)) (car a
))))
760 (setq a
(math-evaluate-expr expr
))
763 (if (eq (car a
) 'float
)
765 (math-reject-arg a
'realp
))))
767 (defvar math-min-or-max
"minimum")
769 ;;; A bracket for a minimum is a < b < c where f(b) < f(a) and f(b) < f(c).
772 (defun math-widen-min (expr a b
)
775 incr c va vb vc u vu r q ulim bc ba qr
)
776 (or b
(setq b
(math-mul a
'(float 101 -
2))))
777 (setq va
(math-min-eval expr a
)
778 vb
(math-min-eval expr b
))
779 (if (math-lessp-float va vb
)
782 (setq c
(math-add-float b
(math-mul-float '(float 161803 -
5)
783 (math-sub-float b a
)))
784 vc
(math-min-eval expr c
))
785 (while (and (not done
) (math-lessp-float vc vb
))
786 (math-working "widen" (list 'intv
0 a c
))
787 (if (= (setq iters
(1- iters
)) 0)
788 (math-reject-arg nil
(format "*Unable to find a %s near the interval"
790 (setq bc
(math-sub-float b c
)
791 ba
(math-sub-float b a
)
792 r
(math-mul-float ba
(math-sub-float vb vc
))
793 q
(math-mul-float bc
(math-sub-float vb va
))
794 qr
(math-sub-float q r
))
795 (if (math-lessp-float (math-abs qr
) '(float 1 -
20))
796 (setq qr
(if (math-negp qr
) '(float -
1 -
20) '(float 1 -
20))))
797 (setq u
(math-sub-float
799 (math-div-float (math-sub-float (math-mul-float bc q
)
800 (math-mul-float ba r
))
801 (math-mul-float '(float 2 0) qr
)))
802 ulim
(math-add-float b
(math-mul-float '(float -
1 2) bc
))
804 (if (if incr
(math-lessp-float b u
) (math-lessp-float u b
))
805 (if (if incr
(math-lessp-float u c
) (math-lessp-float c u
))
806 (if (math-lessp-float (setq vu
(math-min-eval expr u
)) vc
)
810 (if (math-lessp-float vb vu
)
813 (setq u
(math-add-float c
(math-mul-float '(float -
161803 -
5)
815 vu
(math-min-eval expr u
))))
816 (if (if incr
(math-lessp-float u ulim
) (math-lessp-float ulim u
))
817 (if (math-lessp-float (setq vu
(math-min-eval expr u
)) vc
)
820 u
(math-add-float c
(math-mul-float
822 (math-sub-float b c
)))
823 vu
(math-min-eval expr u
)))
825 vu
(math-min-eval expr u
))))
826 (setq u
(math-add-float c
(math-mul-float '(float -
161803 -
5)
828 vu
(math-min-eval expr u
)))
832 (if (math-lessp-float a c
)
833 (list a va b vb c vc
)
834 (list c vc b vb a va
))))
836 (defun math-narrow-min (expr a c intv
)
837 (let ((xvals (list a c
))
838 (yvals (list (math-min-eval expr a
)
839 (math-min-eval expr c
)))
841 (step (math-sub-float c a
))
844 (while (and (<= (setq levels
(1+ levels
)) 5)
848 step
(math-mul-float step
'(float 497 -
3)))
849 (while (and (cdr xp
) (not found
))
850 (setq b
(math-add-float (car xp
) step
))
851 (math-working "search" b
)
852 (setcdr xp
(cons b
(cdr xp
)))
853 (setcdr yp
(cons (math-min-eval expr b
) (cdr yp
)))
854 (if (and (math-lessp-float (nth 1 yp
) (car yp
))
855 (math-lessp-float (nth 1 yp
) (nth 2 yp
)))
859 (if (and (cdr (cdr yp
))
860 (math-lessp-float (nth 1 yp
) (car yp
))
861 (math-lessp-float (nth 1 yp
) (nth 2 yp
)))
866 (list (car xp
) (car yp
)
867 (nth 1 xp
) (nth 1 yp
)
868 (nth 2 xp
) (nth 2 yp
))
869 (or (if (math-lessp-float (car yvals
) (nth 1 yvals
))
870 (and (memq (nth 1 intv
) '(2 3))
871 (let ((min (car yvals
)))
872 (while (and (setq yvals
(cdr yvals
))
873 (math-lessp-float min
(car yvals
))))
875 (list (nth 2 intv
) min
))))
876 (and (memq (nth 1 intv
) '(1 3))
877 (setq yvals
(nreverse yvals
))
878 (let ((min (car yvals
)))
879 (while (and (setq yvals
(cdr yvals
))
880 (math-lessp-float min
(car yvals
))))
882 (list (nth 3 intv
) min
)))))
883 (math-reject-arg nil
(format "*Unable to find a %s in the interval"
884 math-min-or-max
))))))
887 (defun math-brent-min (expr prec a va x vx b vb
)
888 (let ((iters (+ 20 (* 5 prec
)))
893 (tol (list 'float
1 (- -
1 prec
)))
894 (zeps (list 'float
1 (- -
5 prec
)))
896 u vu xm tol1 tol2 etemp p q r xv xw
)
898 (setq xm
(math-mul-float '(float 5 -
1)
899 (math-add-float a b
))
902 (math-mul-float tol
(math-abs x
)))
903 tol2
(math-mul-float tol1
'(float 2 0)))
904 (math-lessp-float (math-sub-float tol2
907 (math-sub-float b a
)))
908 (math-abs (math-sub-float x xm
))))
909 (if (= (setq iters
(1- iters
)) 0)
910 (math-reject-arg nil
(format "*Unable to converge on a %s"
912 (math-working "brent" x
)
913 (if (math-lessp-float (math-abs e
) tol1
)
914 (setq e
(if (math-lessp-float x xm
)
916 (math-sub-float a x
))
917 d
(math-mul-float '(float 381966 -
6) e
))
918 (setq xw
(math-sub-float x w
)
919 r
(math-mul-float xw
(math-sub-float vx vv
))
920 xv
(math-sub-float x v
)
921 q
(math-mul-float xv
(math-sub-float vx vw
))
922 p
(math-sub-float (math-mul-float xv q
)
923 (math-mul-float xw r
))
924 q
(math-mul-float '(float 2 0) (math-sub-float q r
)))
926 (setq p
(math-neg-float p
))
927 (setq q
(math-neg-float q
)))
930 (if (and (math-lessp-float (math-abs p
)
931 (math-abs (math-mul-float
933 (math-mul-float q etemp
))))
934 (math-lessp-float (math-mul-float
935 q
(math-sub-float a x
)) p
)
936 (math-lessp-float p
(math-mul-float
937 q
(math-sub-float b x
))))
939 (setq d
(math-div-float p q
)
940 u
(math-add-float x d
))
941 (if (or (math-lessp-float (math-sub-float u a
) tol2
)
942 (math-lessp-float (math-sub-float b u
) tol2
))
943 (setq d
(if (math-lessp-float xm x
)
944 (math-neg-float tol1
)
946 (setq e
(if (math-lessp-float x xm
)
948 (math-sub-float a x
))
949 d
(math-mul-float '(float 381966 -
6) e
))))
950 (setq u
(math-add-float x
951 (if (math-lessp-float (math-abs d
) tol1
)
953 (math-neg-float tol1
)
956 vu
(math-min-eval expr u
))
957 (if (math-lessp-float vx vu
)
959 (if (math-lessp-float u x
)
963 (not (math-lessp-float vw vu
)))
968 (not (math-lessp-float vv vu
)))
970 (if (math-lessp-float u x
)
979 (defun math-powell-min (expr n guesses prec
)
980 (let* ((f1dim (math-line-min-func expr n
))
981 (xi (calcFunc-idn 1 n
))
982 (p (cons 'vec
(mapcar 'car guesses
)))
984 (ftol (list 'float
1 (- prec
)))
985 (fret (math-min-eval expr p
))
986 fp ptt fptt xit i ibig del diff res
)
992 (while (<= (setq i
(1+ i
)) n
)
994 res
(math-line-min f1dim p
997 p
(let ((calc-internal-prec prec
))
998 (math-normalize (car res
)))
1000 diff
(math-abs (math-sub-float fptt fret
)))
1001 (if (math-lessp-float del diff
)
1005 (math-mul-float ftol
1006 (math-add-float (math-abs fp
)
1008 (math-mul-float '(float 2 0)
1009 (math-abs (math-sub-float fp
1011 (setq ptt
(math-sub (math-mul '(float 2 0) p
) pt
)
1014 fptt
(math-min-eval expr ptt
))
1015 (if (and (math-lessp-float fptt fp
)
1018 (math-mul-float '(float 2 0)
1021 (math-mul-float '(float 2 0)
1024 (math-sqr-float (math-sub-float
1025 (math-sub-float fp fret
) del
)))
1027 (math-sqr-float (math-sub-float fp fptt
)))))
1029 (setq res
(math-line-min f1dim p xit n prec
)
1033 (while (<= (setq i
(1+ i
)) n
)
1034 (setcar (nthcdr ibig
(nth i xi
))
1035 (nth i
(nth 1 res
)))))))
1036 (list 'vec p fret
)))
1038 (defun math-line-min-func (expr n
)
1040 (while (< (setq m
(1+ m
)) n
)
1041 (set (nth 2 (aref math-min-vars m
))
1044 '(var DUMMY var-DUMMY
)
1045 (list 'calcFunc-mrow
'(var line-xi line-xi
) (1+ m
)))
1046 (list 'calcFunc-mrow
'(var line-p line-p
) (1+ m
)))))
1047 (math-evaluate-expr expr
)))
1049 (defun math-line-min (f1dim line-p line-xi n prec
)
1050 (let* ((var-DUMMY nil
)
1051 (expr (math-evaluate-expr f1dim
))
1052 (params (math-widen-min expr
'(float 0 0) '(float 1 0)))
1053 (res (apply 'math-brent-min expr prec params
))
1054 (xi (math-mul (nth 1 res
) line-xi
)))
1055 (list (math-add line-p xi
) xi
(nth 2 res
))))
1058 (defvar math-min-vars
[(var DUMMY var-DUMMY
)])
1060 (defun math-find-minimum (expr var guess min-widen
)
1061 (let* ((calc-symbolic-mode nil
)
1064 (isvec (math-vectorp var
))
1066 (or (math-vectorp var
)
1067 (setq var
(list 'vec var
)))
1068 (or (math-vectorp guess
)
1069 (setq guess
(list 'vec guess
)))
1070 (or (= (length var
) (length guess
))
1071 (math-dimension-error))
1072 (while (setq var
(cdr var
) guess
(cdr guess
))
1073 (or (eq (car-safe (car var
)) 'var
)
1074 (math-reject-arg (car vg
) "*Expected a variable"))
1075 (or (math-expr-contains expr
(car var
))
1076 (math-reject-arg (car var
)
1077 "*Formula does not contain specified variable"))
1078 (while (>= (1+ n
) (length math-min-vars
))
1079 (let ((symb (intern (concat "math-min-v"
1081 (length math-min-vars
))))))
1082 (setq math-min-vars
(vconcat math-min-vars
1083 (vector (list 'var symb symb
))))))
1084 (set (nth 2 (aref math-min-vars n
)) nil
)
1085 (set (nth 2 (aref math-min-vars
(1+ n
))) nil
)
1086 (if (math-complexp (car guess
))
1087 (setq expr
(math-expr-subst expr
1089 (list '+ (aref math-min-vars n
)
1091 (aref math-min-vars
(1+ n
))
1093 guesses
(let ((g (math-float (math-complex (car guess
)))))
1094 (cons (list (nth 2 g
) nil nil
)
1095 (cons (list (nth 1 g
) nil nil t
)
1098 (setq expr
(math-expr-subst expr
1100 (aref math-min-vars n
))
1101 guesses
(cons (if (math-realp (car guess
))
1102 (list (math-float (car guess
)) nil nil
)
1103 (if (and (eq (car-safe (car guess
)) 'intv
)
1104 (math-constp (car guess
)))
1106 (math-add (nth 2 (car guess
))
1107 (nth 3 (car guess
)))
1109 (math-float (nth 2 (car guess
)))
1110 (math-float (nth 3 (car guess
)))
1112 (math-reject-arg (car guess
) 'realp
)))
1115 (setq guesses
(nreverse guesses
)
1116 expr
(math-evaluate-expr expr
))
1118 (let* ((params (if (nth 1 (car guesses
))
1120 (math-widen-min expr
1121 (nth 1 (car guesses
))
1122 (nth 2 (car guesses
)))
1123 (math-narrow-min expr
1124 (nth 1 (car guesses
))
1125 (nth 2 (car guesses
))
1126 (nth 3 (car guesses
))))
1127 (math-widen-min expr
1130 (prec calc-internal-prec
)
1131 (res (if (cdr (cdr params
))
1132 (math-with-extra-prec (+ calc-internal-prec
2)
1133 (apply 'math-brent-min expr prec params
))
1134 (cons 'vec params
))))
1136 (list 'vec
(list 'vec
(nth 1 res
)) (nth 2 res
))
1138 (let* ((prec calc-internal-prec
)
1139 (res (math-with-extra-prec (+ calc-internal-prec
2)
1140 (math-powell-min expr n guesses prec
)))
1143 (while (setq p
(cdr p
))
1144 (if (nth 3 (car guesses
))
1146 (nconc vec
(list (math-normalize
1147 (list 'cplx
(car p
) (nth 1 p
)))))
1149 guesses
(cdr guesses
)))
1150 (nconc vec
(list (car p
))))
1151 (setq guesses
(cdr guesses
)))
1153 (list 'vec vec
(nth 2 res
))
1154 (list 'vec
(nth 1 vec
) (nth 2 res
)))))))
1156 (defun calcFunc-minimize (expr var guess
)
1157 (let ((calc-internal-prec (max (/ calc-internal-prec
2) 3))
1158 (math-min-or-max "minimum"))
1159 (math-find-minimum (math-normalize expr
)
1160 (math-normalize var
)
1161 (math-normalize guess
) nil
)))
1163 (defun calcFunc-wminimize (expr var guess
)
1164 (let ((calc-internal-prec (max (/ calc-internal-prec
2) 3))
1165 (math-min-or-max "minimum"))
1166 (math-find-minimum (math-normalize expr
)
1167 (math-normalize var
)
1168 (math-normalize guess
) t
)))
1170 (defun calcFunc-maximize (expr var guess
)
1171 (let* ((calc-internal-prec (max (/ calc-internal-prec
2) 3))
1172 (math-min-or-max "maximum")
1173 (res (math-find-minimum (math-normalize (math-neg expr
))
1174 (math-normalize var
)
1175 (math-normalize guess
) nil
)))
1176 (list 'vec
(nth 1 res
) (math-neg (nth 2 res
)))))
1178 (defun calcFunc-wmaximize (expr var guess
)
1179 (let* ((calc-internal-prec (max (/ calc-internal-prec
2) 3))
1180 (math-min-or-max "maximum")
1181 (res (math-find-minimum (math-normalize (math-neg expr
))
1182 (math-normalize var
)
1183 (math-normalize guess
) t
)))
1184 (list 'vec
(nth 1 res
) (math-neg (nth 2 res
)))))
1189 ;;; The following algorithms come from Numerical Recipes, chapter 3.
1191 (defun calcFunc-polint (data x
)
1192 (or (math-matrixp data
) (math-reject-arg data
'matrixp
))
1193 (or (= (length data
) 3)
1194 (math-reject-arg data
"*Wrong number of data rows"))
1195 (or (> (length (nth 1 data
)) 2)
1196 (math-reject-arg data
"*Too few data points"))
1197 (if (and (math-vectorp x
) (or (math-constp x
) math-expand-formulas
))
1198 (cons 'vec
(mapcar (function (lambda (x) (calcFunc-polint data x
)))
1200 (or (math-objectp x
) math-expand-formulas
(math-reject-arg x
'objectp
))
1201 (math-with-extra-prec 2
1202 (cons 'vec
(math-poly-interp (cdr (nth 1 data
)) (cdr (nth 2 data
)) x
1204 (put 'calcFunc-polint
'math-expandable t
)
1207 (defun calcFunc-ratint (data x
)
1208 (or (math-matrixp data
) (math-reject-arg data
'matrixp
))
1209 (or (= (length data
) 3)
1210 (math-reject-arg data
"*Wrong number of data rows"))
1211 (or (> (length (nth 1 data
)) 2)
1212 (math-reject-arg data
"*Too few data points"))
1213 (if (and (math-vectorp x
) (or (math-constp x
) math-expand-formulas
))
1214 (cons 'vec
(mapcar (function (lambda (x) (calcFunc-ratint data x
)))
1216 (or (math-objectp x
) math-expand-formulas
(math-reject-arg x
'objectp
))
1217 (math-with-extra-prec 2
1218 (cons 'vec
(math-poly-interp (cdr (nth 1 data
)) (cdr (nth 2 data
)) x
1219 (cdr (cdr (cdr (nth 1 data
)))))))))
1220 (put 'calcFunc-ratint
'math-expandable t
)
1223 (defun math-poly-interp (xa ya x ratp
)
1224 (let ((n (length xa
))
1228 (c (copy-sequence ya
))
1229 (d (copy-sequence ya
))
1232 y dy
(xp xa
) xpm cp dp temp
)
1233 (while (<= (setq i
(1+ i
)) n
)
1234 (setq xax
(cons (math-sub (car xp
) x
) xax
)
1236 temp
(math-abs (car xax
)))
1237 (if (or (null dif
) (math-lessp temp dif
))
1240 (setq xax
(nreverse xax
)
1243 (if (math-zerop dif
)
1245 (while (< (setq m
(1+ m
)) n
)
1251 (while (<= (setq i
(1+ i
)) (- n m
))
1253 (let ((t2 (math-div (math-mul (car xp
) (car dp
)) (car xpm
))))
1254 (setq temp
(math-div (math-sub (nth 1 cp
) (car dp
))
1255 (math-sub t2
(nth 1 cp
))))
1256 (setcar dp
(math-mul (nth 1 cp
) temp
))
1257 (setcar cp
(math-mul t2 temp
)))
1258 (if (math-equal (car xp
) (car xpm
))
1259 (math-reject-arg (cons 'vec xa
) "*Duplicate X values"))
1260 (setq temp
(math-div (math-sub (nth 1 cp
) (car dp
))
1261 (math-sub (car xp
) (car xpm
))))
1262 (setcar dp
(math-mul (car xpm
) temp
))
1263 (setcar cp
(math-mul (car xp
) temp
)))
1268 (if (< (+ ns ns
) (- n m
))
1269 (setq dy
(nth ns c
))
1272 (setq y
(math-add y dy
)))
1277 ;;; The following algorithms come from Numerical Recipes, chapter 4.
1279 (defun calcFunc-ninteg (expr var lo hi
)
1280 (setq lo
(math-evaluate-expr lo
)
1281 hi
(math-evaluate-expr hi
))
1282 (or (math-numberp lo
) (math-infinitep lo
) (math-reject-arg lo
'numberp
))
1283 (or (math-numberp hi
) (math-infinitep hi
) (math-reject-arg hi
'numberp
))
1284 (if (math-lessp hi lo
)
1285 (math-neg (calcFunc-ninteg expr var hi lo
))
1286 (setq expr
(math-expr-subst expr var
'(var DUMMY var-DUMMY
)))
1287 (let ((var-DUMMY nil
)
1288 (calc-symbolic-mode nil
)
1289 (calc-prefer-frac nil
)
1291 (setq expr
(math-evaluate-expr expr
))
1292 (if (equal lo
'(neg (var inf var-inf
)))
1293 (let ((thi (if (math-lessp hi
'(float -
2 0))
1295 (setq sum
(math-ninteg-romberg
1296 'math-ninteg-midpoint expr
1297 (math-float lo
) (math-float thi
) 'inf
)
1299 (if (equal hi
'(var inf var-inf
))
1300 (let ((tlo (if (math-lessp '(float 2 0) lo
)
1302 (setq sum
(math-add sum
1303 (math-ninteg-romberg
1304 'math-ninteg-midpoint expr
1305 (math-float tlo
) (math-float hi
) 'inf
))
1307 (or (math-equal lo hi
)
1308 (setq sum
(math-add sum
1309 (math-ninteg-romberg
1310 'math-ninteg-midpoint expr
1311 (math-float lo
) (math-float hi
) nil
))))
1315 ;;; Open Romberg method; "qromo" in section 4.4.
1316 (defun math-ninteg-romberg (func expr lo hi mode
)
1317 (let ((curh '(float 1 0))
1322 (prec calc-internal-prec
)
1324 (math-with-extra-prec 2
1325 ;; Limit on "j" loop must be 14 or less to keep "it" from overflowing.
1326 (or (while (and (null ss
) (<= (setq j
(1+ j
)) 8))
1327 (setq s
(nconc s
(list (funcall func expr lo hi mode
)))
1328 h
(nconc h
(list curh
)))
1330 (let ((res (math-poly-interp h s
'(float 0 0) nil
)))
1331 (if (math-lessp (math-abs (nth 1 res
))
1332 (calcFunc-scf (math-abs (car res
))
1334 (setq math-ninteg-convergence j
1339 (setq curh
(math-div-float curh
'(float 9 0))))
1341 (math-reject-arg nil
(format "*Integral failed to converge"))))))
1344 (defun math-ninteg-evaluate (expr x mode
)
1346 (setq x
(math-div '(float 1 0) x
)))
1347 (let* ((var-DUMMY x
)
1348 (res (math-evaluate-expr expr
)))
1349 (or (Math-numberp res
)
1350 (math-reject-arg res
"*Integrand does not evaluate to a number"))
1352 (setq res
(math-mul res
(math-sqr x
))))
1356 (defun math-ninteg-midpoint (expr lo hi mode
) ; uses "integ-temp"
1358 (let ((math-infinite-mode t
) temp
)
1359 (setq temp
(math-div 1 lo
)
1363 (let* ((it3 (* 3 (car integ-temp
)))
1364 (math-working-step-2 (* 2 (car integ-temp
)))
1365 (math-working-step 0)
1366 (range (math-sub hi lo
))
1367 (del (math-div range
(math-float it3
)))
1368 (del2 (math-add del del
))
1369 (del3 (math-add del del2
))
1370 (x (math-add lo
(math-mul '(float 5 -
1) del
)))
1373 (while (<= (setq j
(1+ j
)) (car integ-temp
))
1374 (setq math-working-step
(1+ math-working-step
)
1375 temp
(math-ninteg-evaluate expr x mode
)
1376 math-working-step
(1+ math-working-step
)
1377 sum
(math-add sum
(math-add temp
(math-ninteg-evaluate
1378 expr
(math-add x del2
)
1380 x
(math-add x del3
)))
1381 (setq integ-temp
(list it3
1382 (math-add (math-div (nth 1 integ-temp
)
1384 (math-mul sum del
)))))
1385 (setq integ-temp
(list 1 (math-mul
1387 (math-ninteg-evaluate
1389 (math-mul (math-add lo hi
) '(float 5 -
1))
1397 ;;; The following algorithms come from Numerical Recipes, chapter 14.
1399 (defvar math-dummy-vars
[(var DUMMY var-DUMMY
)])
1400 (defvar math-dummy-counter
0)
1401 (defun math-dummy-variable ()
1402 (if (= math-dummy-counter
(length math-dummy-vars
))
1403 (let ((symb (intern (format "math-dummy-%d" math-dummy-counter
))))
1404 (setq math-dummy-vars
(vconcat math-dummy-vars
1405 (vector (list 'var symb symb
))))))
1406 (set (nth 2 (aref math-dummy-vars math-dummy-counter
)) nil
)
1408 (aref math-dummy-vars math-dummy-counter
)
1409 (setq math-dummy-counter
(1+ math-dummy-counter
))))
1411 (defvar math-in-fit
0)
1412 (defvar calc-fit-to-trail nil
)
1414 (defun calcFunc-fit (expr vars
&optional coefs data
)
1415 (let ((math-in-fit 10))
1416 (math-with-extra-prec 2
1417 (math-general-fit expr vars coefs data nil
))))
1419 (defun calcFunc-efit (expr vars
&optional coefs data
)
1420 (let ((math-in-fit 10))
1421 (math-with-extra-prec 2
1422 (math-general-fit expr vars coefs data
'sdev
))))
1424 (defun calcFunc-xfit (expr vars
&optional coefs data
)
1425 (let ((math-in-fit 10))
1426 (math-with-extra-prec 2
1427 (math-general-fit expr vars coefs data
'full
))))
1429 (defun math-general-fit (expr vars coefs data mode
)
1430 (let ((calc-simplify-mode nil
)
1431 (math-dummy-counter math-dummy-counter
)
1433 (extended (eq mode
'full
))
1434 (first-coef math-dummy-counter
)
1438 have-sdevs need-chisq chisq
1446 (var-YVAL nil
) (var-YVALX nil
)
1448 n nn m mm v dummy p
)
1450 ;; Validate and parse arguments.
1455 (if (math-vectorp expr
)
1456 (if (memq (length expr
) '(3 4))
1461 (math-dimension-error))
1465 (or (math-matrixp data
) (math-reject-arg data
'matrixp
))
1466 (setq v
(1- (length data
))
1467 n
(1- (length (nth 1 data
))))
1468 (or (math-vectorp vars
) (null vars
)
1469 (setq vars
(list 'vec vars
)))
1470 (or (math-vectorp coefs
) (null coefs
)
1471 (setq coefs
(list 'vec coefs
)))
1473 (setq coefs
(cons 'vec
(math-all-vars-but expr vars
))))
1475 (if (<= (1- (length coefs
)) v
)
1476 (math-reject-arg coefs
"*Not enough variables in model")
1477 (setq coefs
(copy-sequence coefs
))
1478 (let ((p (nthcdr (- (length coefs
) v
1479 (if (eq (car-safe expr
) 'calcFunc-eq
) 1 0))
1481 (setq vars
(cons 'vec
(cdr p
)))
1483 (or (= (1- (length vars
)) v
)
1485 (math-reject-arg vars
"*Number of variables does not match data"))
1486 (setq m
(1- (length coefs
)))
1488 (math-reject-arg coefs
"*Need at least one parameter"))
1490 ;; Rewrite expr in terms of fitparam and fitvar, make into an equation.
1492 (while (setq p
(cdr p
))
1493 (or (eq (car-safe (car p
)) 'var
)
1494 (math-reject-arg (car p
) "*Expected a variable"))
1495 (setq dummy
(math-dummy-variable)
1496 expr
(math-expr-subst expr
(car p
)
1497 (list 'calcFunc-fitparam
1498 (- math-dummy-counter first-coef
)))))
1499 (setq first-var math-dummy-counter
1501 (while (setq p
(cdr p
))
1502 (or (eq (car-safe (car p
)) 'var
)
1503 (math-reject-arg (car p
) "*Expected a variable"))
1504 (setq dummy
(math-dummy-variable)
1505 expr
(math-expr-subst expr
(car p
)
1506 (list 'calcFunc-fitvar
1507 (- math-dummy-counter first-var
)))))
1508 (if (< math-dummy-counter
(+ first-var v
))
1509 (setq dummy
(math-dummy-variable))) ; dependent variable may be unnamed
1512 (or (eq (car-safe expr
) 'calcFunc-eq
)
1513 (setq expr
(list 'calcFunc-eq
(list 'calcFunc-fitvar v
) expr
)))
1515 (let ((calc-symbolic-mode nil
))
1517 ;; Apply rewrites to put expr into a linear-like form.
1518 (setq expr
(math-evaluate-expr expr
)
1519 expr
(math-rewrite (list 'calcFunc-fitmodel expr
)
1520 '(var FitRules var-FitRules
))
1522 expr
(math-evaluate-expr expr
))
1523 (or (and (eq (car-safe expr
) 'calcFunc-fitsystem
)
1525 (math-vectorp (nth 2 expr
))
1526 (math-vectorp (nth 3 expr
))
1527 (> (length (nth 2 expr
)) 1)
1528 (= (length (nth 3 expr
)) (1+ m
)))
1529 (math-reject-arg plain-expr
"*Model expression is too complex"))
1530 (setq y-filter
(nth 1 expr
)
1531 x-funcs
(vconcat (cdr (nth 2 expr
)))
1532 coef-filters
(nth 3 expr
)
1533 mm
(length x-funcs
))
1534 (if (equal y-filter y-dummy
)
1535 (setq y-filter nil
))
1537 ;; Build the (square) system of linear equations to be solved.
1538 (setq beta
(cons 'vec
(make-list mm
0))
1539 covar
(cons 'vec
(mapcar 'copy-sequence
(make-list mm beta
))))
1540 (let* ((ptrs (vconcat (cdr data
)))
1542 (xvals (make-vector mm
0))
1544 j k xval yval sigmasqr wt covj covjk covk betaj lud
)
1545 (while (<= (setq i
(1+ i
)) n
)
1547 ;; Assign various independent variables for this data point.
1551 (aset ptrs j
(cdr (aref ptrs j
)))
1552 (setq xval
(car (aref ptrs j
)))
1556 (if (eq (car-safe xval
) 'sdev
)
1557 (setq sigmasqr
(math-add (math-sqr (nth 2 xval
))
1561 (setq xval
(math-make-sdev xval
1562 (math-sqrt sigmasqr
))))))
1563 (if (eq (car-safe xval
) 'sdev
)
1564 (setq sigmasqr
(math-add (math-sqr (nth 2 xval
))
1566 xval
(nth 1 xval
))))
1567 (set (nth 2 (aref math-dummy-vars
(+ first-var j
))) xval
)
1570 ;; Compute Y value for this data point.
1572 (setq yval
(math-evaluate-expr y-filter
))
1573 (setq yval
(symbol-value (nth 2 y-dummy
))))
1574 (if (eq (car-safe yval
) 'sdev
)
1575 (setq sigmasqr
(math-sqr (nth 2 yval
))
1578 (setq have-sdevs sigmasqr
1579 need-chisq
(or extended
1580 (and (eq mode
'sdev
) (not have-sdevs
)))))
1584 (setq isigsq
(math-div 1 sigmasqr
))
1586 (setq weights
(cons isigsq weights
))))
1587 (math-reject-arg yval
"*Mixed error forms and plain numbers"))
1589 (math-reject-arg yval
"*Mixed error forms and plain numbers")))
1591 ;; Compute X values for this data point and update covar and beta.
1592 (if (eq (car-safe xval
) 'sdev
)
1593 (set (nth 2 y-dummy
) (nth 1 xval
)))
1598 (setq wt
(math-evaluate-expr (aref x-funcs j
)))
1600 (setq wt
(math-mul wt isigsq
)
1602 covjk
(car (setq covj
(cdr covj
)))
1605 (setq covjk
(cdr covjk
))
1606 (setcar covjk
(math-add (car covjk
)
1607 (math-mul wt
(aref xvals k
))))
1609 (setcar betaj
(math-add (car betaj
) (math-mul wt yval
)))
1612 (setq xy-values
(cons (append xvals
(list yval
)) xy-values
))))
1614 ;; Fill in symmetric half of covar matrix.
1617 (while (< j
(1- mm
))
1620 covjk
(nthcdr j
(car (setq covj
(cdr covj
))))
1621 covk
(nthcdr j covar
))
1622 (while (< (setq k
(1+ k
)) mm
)
1623 (setq covjk
(cdr covjk
)
1625 (setcar covjk
(nth j
(car covk
))))))
1627 ;; Solve the linear system.
1630 (setq covar
(math-matrix-inv-raw covar
))
1632 (setq beta
(math-mul covar beta
))
1633 (if (math-zerop (math-abs beta
))
1634 (setq covar
(calcFunc-diag 0 (1- (length beta
))))
1635 (math-reject-arg orig-expr
"*Singular matrix")))
1636 (or (math-vectorp covar
)
1637 (setq covar
(list 'vec
(list 'vec covar
)))))
1638 (setq beta
(math-div beta covar
)))
1640 ;; Compute chi-square statistic if necessary.
1648 (while (setq bp
(cdr bp
))
1649 (setq sum
(math-add sum
(math-mul (car bp
) (car xp
)))
1651 (setq sum
(math-sqr (math-sub (car xp
) sum
)))
1652 (if weights
(setq sum
(math-mul sum
(car weights
))))
1653 (setq chisq
(math-add chisq sum
)
1654 weights
(cdr weights
)
1655 xy-values
(cdr xy-values
)))))
1657 ;; Convert coefficients back into original terms.
1658 (setq new-coefs
(copy-sequence beta
))
1659 (let* ((bp new-coefs
)
1664 (and mode
(not have-sdevs
)
1665 (setq sigdat
(if (<= n mm
)
1667 (math-div chisq
(- n mm
)))))
1669 (while (setq bp
(cdr bp
))
1670 (setcar bp
(math-make-sdev
1672 (math-sqrt (math-mul (nth (setq j
(1+ j
))
1673 (car (setq cp
(cdr cp
))))
1675 (setq new-coefs
(math-evaluate-expr coef-filters
))
1676 (if calc-fit-to-trail
1677 (let ((bp new-coefs
)
1680 (while (setq bp
(cdr bp
) cp
(cdr cp
))
1681 (setq vec
(cons (list 'calcFunc-eq
(car cp
) (car bp
)) vec
)))
1682 (setq calc-fit-to-trail
(cons 'vec
(nreverse vec
)))))))
1684 ;; Substitute best-fit coefficients back into original formula.
1685 (setq expr
(math-multi-subst
1690 (setq vec
(cons (list 'calcFunc-fitvar n
) vec
)
1694 (setq vec
(cons (list 'calcFunc-fitparam n
) vec
)
1697 (append (cdr new-coefs
) (cdr vars
))))
1699 ;; Package the result.
1702 (list 'vec expr beta covar
1703 (let ((p coef-filters
)
1705 (while (and (setq n
(1+ n
) p
(cdr p
))
1706 (eq (car-safe (car p
)) 'calcFunc-fitdummy
)
1707 (eq (nth 1 (car p
)) n
)))
1712 (if (and have-sdevs
(> n mm
))
1713 (list 'calcFunc-utpc chisq
(- n mm
))
1714 '(var nan var-nan
)))
1718 (defun calcFunc-fitvar (x)
1719 (if (>= math-in-fit
2)
1721 (setq x
(aref math-dummy-vars
(+ first-var x -
1)))
1722 (or (calc-var-value (nth 2 x
)) x
))
1723 (math-reject-arg x
)))
1725 (defun calcFunc-fitparam (x)
1726 (if (>= math-in-fit
2)
1728 (setq x
(aref math-dummy-vars
(+ first-coef x -
1)))
1729 (or (calc-var-value (nth 2 x
)) x
))
1730 (math-reject-arg x
)))
1732 (defun calcFunc-fitdummy (x)
1733 (if (= math-in-fit
3)
1735 (math-reject-arg x
)))
1737 (defun calcFunc-hasfitvars (expr)
1738 (if (Math-primp expr
)
1740 (if (eq (car expr
) 'calcFunc-fitvar
)
1742 (apply 'max
(mapcar 'calcFunc-hasfitvars
(cdr expr
))))))
1744 (defun calcFunc-hasfitparams (expr)
1745 (if (Math-primp expr
)
1747 (if (eq (car expr
) 'calcFunc-fitparam
)
1749 (apply 'max
(mapcar 'calcFunc-hasfitparams
(cdr expr
))))))
1752 (defun math-all-vars-but (expr but
)
1753 (let* ((vars (math-all-vars-in expr
))
1756 (setq vars
(delq (assoc (car-safe p
) vars
) vars
)
1758 (sort (mapcar 'car vars
)
1759 (function (lambda (x y
) (string< (nth 1 x
) (nth 1 y
)))))))
1761 (defun math-all-vars-in (expr)
1764 (math-all-vars-rec expr
)
1767 (defun math-all-vars-rec (expr)
1768 (if (Math-primp expr
)
1769 (if (eq (car-safe expr
) 'var
)
1770 (or (math-const-var expr
)
1771 (if (setq found
(assoc expr vars
))
1772 (setcdr found
(1+ (cdr found
)))
1773 (setq vars
(cons (cons expr
1) vars
)))))
1774 (while (setq expr
(cdr expr
))
1775 (math-all-vars-rec (car expr
)))))
1777 ;;; calcalg3.el ends here