calcalg3.el 59.5 KB
Newer Older
1 2
;;; calcalg3.el --- more algebraic functions for Calc

Jay Belanger's avatar
Jay Belanger committed
3
;; Copyright (C) 1990, 1991, 1992, 1993, 2001, 2002, 2003, 2004,
Jay Belanger's avatar
Jay Belanger committed
4
;;   2005, 2006 Free Software Foundation, Inc.
5 6

;; Author: David Gillespie <daveg@synaptics.com>
7
;; Maintainer: Jay Belanger <belanger@truman.edu>
Eli Zaretskii's avatar
Eli Zaretskii committed
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

;; This file is part of GNU Emacs.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY.  No author or distributor
;; accepts responsibility to anyone for the consequences of using it
;; or for whether it serves any particular purpose or works at all,
;; unless he says so in writing.  Refer to the GNU Emacs General Public
;; License for full details.

;; Everyone is granted permission to copy, modify and redistribute
;; GNU Emacs, but only under the conditions described in the
;; GNU Emacs General Public License.   A copy of this license is
;; supposed to have been given to you along with GNU Emacs so you
;; can know your rights and responsibilities.  It should be in a
;; file named COPYING.  Among other things, the copyright notice
;; and this notice must be preserved on all copies.

26
;;; Commentary:
Eli Zaretskii's avatar
Eli Zaretskii committed
27

28
;;; Code:
Eli Zaretskii's avatar
Eli Zaretskii committed
29 30 31

;; This file is autoloaded from calc-ext.el.

Jay Belanger's avatar
Jay Belanger committed
32
(require 'calc-ext)
Eli Zaretskii's avatar
Eli Zaretskii committed
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
(require 'calc-macs)

(defun calc-find-root (var)
  (interactive "sVariable(s) to solve for: ")
  (calc-slow-wrapper
   (let ((func (if (calc-is-hyperbolic) 'calcFunc-wroot 'calcFunc-root)))
     (if (or (equal var "") (equal var "$"))
	 (calc-enter-result 2 "root" (list func
					   (calc-top-n 3)
					   (calc-top-n 1)
					   (calc-top-n 2)))
       (let ((var (if (and (string-match ",\\|[^ ] +[^ ]" var)
			   (not (string-match "\\[" var)))
		      (math-read-expr (concat "[" var "]"))
		    (math-read-expr var))))
	 (if (eq (car-safe var) 'error)
	     (error "Bad format in expression: %s" (nth 1 var)))
	 (calc-enter-result 1 "root" (list func
					   (calc-top-n 2)
					   var
53
					   (calc-top-n 1))))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77

(defun calc-find-minimum (var)
  (interactive "sVariable(s) to minimize over: ")
  (calc-slow-wrapper
   (let ((func (if (calc-is-inverse)
		   (if (calc-is-hyperbolic)
		       'calcFunc-wmaximize 'calcFunc-maximize)
		 (if (calc-is-hyperbolic)
		     'calcFunc-wminimize 'calcFunc-minimize)))
	 (tag (if (calc-is-inverse) "max" "min")))
     (if (or (equal var "") (equal var "$"))
	 (calc-enter-result 2 tag (list func
					(calc-top-n 3)
					(calc-top-n 1)
					(calc-top-n 2)))
       (let ((var (if (and (string-match ",\\|[^ ] +[^ ]" var)
			   (not (string-match "\\[" var)))
		      (math-read-expr (concat "[" var "]"))
		    (math-read-expr var))))
	 (if (eq (car-safe var) 'error)
	     (error "Bad format in expression: %s" (nth 1 var)))
	 (calc-enter-result 1 tag (list func
					(calc-top-n 2)
					var
78
					(calc-top-n 1))))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
79 80 81 82

(defun calc-find-maximum (var)
  (interactive "sVariable to maximize over: ")
  (calc-invert-func)
83
  (calc-find-minimum var))
Eli Zaretskii's avatar
Eli Zaretskii committed
84 85 86 87 88 89 90 91 92 93 94 95 96


(defun calc-poly-interp (arg)
  (interactive "P")
  (calc-slow-wrapper
   (let ((data (calc-top 2)))
     (if (or (consp arg) (eq arg 0) (eq arg 2))
	 (setq data (cons 'vec (calc-top-list 2 2)))
       (or (null arg)
	   (error "Bad prefix argument")))
     (if (calc-is-hyperbolic)
	 (calc-enter-result 1 "rati" (list 'calcFunc-ratint data (calc-top 1)))
       (calc-enter-result 1 "poli" (list 'calcFunc-polint data
97
					 (calc-top 1)))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
98

99 100 101 102 103 104
;; The variables calc-curve-nvars, calc-curve-varnames, calc-curve-model and calc-curve-coefnames are local to calc-curve-fit, but are
;; used by calc-get-fit-variables which is called by calc-curve-fit.
(defvar calc-curve-nvars)
(defvar calc-curve-varnames)
(defvar calc-curve-model)
(defvar calc-curve-coefnames)
Eli Zaretskii's avatar
Eli Zaretskii committed
105

106 107 108
(defvar calc-curve-fit-history nil
  "History for calc-curve-fit.")

109 110
(defun calc-curve-fit (arg &optional calc-curve-model 
                           calc-curve-coefnames calc-curve-varnames)
Eli Zaretskii's avatar
Eli Zaretskii committed
111 112 113 114 115 116 117
  (interactive "P")
  (calc-slow-wrapper
   (setq calc-aborted-prefix nil)
   (let ((func (if (calc-is-inverse) 'calcFunc-xfit
		 (if (calc-is-hyperbolic) 'calcFunc-efit
		   'calcFunc-fit)))
	 key (which 0)
118
	 n calc-curve-nvars temp data
Eli Zaretskii's avatar
Eli Zaretskii committed
119 120 121 122 123 124 125 126 127 128 129
	 (homog nil)
	 (msgs '( "(Press ? for help)"
		  "1 = linear or multilinear"
		  "2-9 = polynomial fits; i = interpolating polynomial"
		  "p = a x^b, ^ = a b^x"
		  "e = a exp(b x), x = exp(a + b x), l = a + b ln(x)"
		  "E = a 10^(b x), X = 10^(a + b x), L = a + b log10(x)"
		  "q = a + b (x-c)^2"
		  "g = (a/b sqrt(2 pi)) exp(-0.5*((x-c)/b)^2)"
		  "h prefix = homogeneous model (no constant term)"
		  "' = alg entry, $ = stack, u = Model1, U = Model2")))
130
     (while (not calc-curve-model)
Eli Zaretskii's avatar
Eli Zaretskii committed
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
       (message "Fit to model: %s:%s"
		(nth which msgs)
		(if homog " h" ""))
       (setq key (read-char))
       (cond ((= key ?\C-g)
	      (keyboard-quit))
	     ((= key ??)
	      (setq which (% (1+ which) (length msgs))))
	     ((memq key '(?h ?H))
	      (setq homog (not homog)))
	     ((progn
		(if (eq key ?\$)
		    (setq n 1)
		  (setq n 0))
		(cond ((null arg)
		       (setq n (1+ n)
			     data (calc-top n)))
		      ((or (consp arg) (eq arg 0))
		       (setq n (+ n 2)
			     data (calc-top n)
			     data (if (math-matrixp data)
				      (append data (list (calc-top (1- n))))
				    (list 'vec data (calc-top (1- n))))))
		      ((> (setq arg (prefix-numeric-value arg)) 0)
		       (setq data (cons 'vec (calc-top-list arg (1+ n)))
			     n (+ n arg)))
		      (t (error "Bad prefix argument")))
		(or (math-matrixp data) (not (cdr (cdr data)))
		    (error "Data matrix is not a matrix!"))
160 161 162
		(setq calc-curve-nvars (- (length data) 2)
		      calc-curve-coefnames nil
		      calc-curve-varnames nil)
Eli Zaretskii's avatar
Eli Zaretskii committed
163 164
		nil))
	     ((= key ?1)  ; linear or multilinear
165 166 167 168
	      (calc-get-fit-variables calc-curve-nvars 
                                      (1+ calc-curve-nvars) (and homog 0))
	      (setq calc-curve-model (math-mul calc-curve-coefnames
				    (cons 'vec (cons 1 (cdr calc-curve-varnames))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
169 170
	     ((and (>= key ?2) (<= key ?9))   ; polynomial
	      (calc-get-fit-variables 1 (- key ?0 -1) (and homog 0))
171 172 173
	      (setq calc-curve-model 
                    (math-build-polynomial-expr (cdr calc-curve-coefnames)
                                                (nth 1 calc-curve-varnames))))
Eli Zaretskii's avatar
Eli Zaretskii committed
174 175 176
	     ((= key ?i)  ; exact polynomial
	      (calc-get-fit-variables 1 (1- (length (nth 1 data)))
				      (and homog 0))
177 178 179
	      (setq calc-curve-model 
                    (math-build-polynomial-expr (cdr calc-curve-coefnames)
                                                (nth 1 calc-curve-varnames))))
Eli Zaretskii's avatar
Eli Zaretskii committed
180
	     ((= key ?p)  ; power law
181 182 183
	      (calc-get-fit-variables calc-curve-nvars 
                                      (1+ calc-curve-nvars) (and homog 1))
	      (setq calc-curve-model (math-mul (nth 1 calc-curve-coefnames)
Eli Zaretskii's avatar
Eli Zaretskii committed
184 185 186 187
				    (calcFunc-reduce
				     '(var mul var-mul)
				     (calcFunc-map
				      '(var pow var-pow)
188 189
				      calc-curve-varnames
				      (cons 'vec (cdr (cdr calc-curve-coefnames))))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
190
	     ((= key ?^)  ; exponential law
191 192 193
	      (calc-get-fit-variables calc-curve-nvars 
                                      (1+ calc-curve-nvars) (and homog 1))
	      (setq calc-curve-model (math-mul (nth 1 calc-curve-coefnames)
Eli Zaretskii's avatar
Eli Zaretskii committed
194 195 196 197
				    (calcFunc-reduce
				     '(var mul var-mul)
				     (calcFunc-map
				      '(var pow var-pow)
198 199
				      (cons 'vec (cdr (cdr calc-curve-coefnames)))
				      calc-curve-varnames)))))
Eli Zaretskii's avatar
Eli Zaretskii committed
200
	     ((memq key '(?e ?E))
201 202 203
	      (calc-get-fit-variables calc-curve-nvars 
                                      (1+ calc-curve-nvars) (and homog 1))
	      (setq calc-curve-model (math-mul (nth 1 calc-curve-coefnames)
Eli Zaretskii's avatar
Eli Zaretskii committed
204 205 206 207 208 209 210 211 212 213
				    (calcFunc-reduce
				     '(var mul var-mul)
				     (calcFunc-map
				      (if (eq key ?e)
					  '(var exp var-exp)
					'(calcFunc-lambda
					  (var a var-a)
					  (^ 10 (var a var-a))))
				      (calcFunc-map
				       '(var mul var-mul)
214 215
				       (cons 'vec (cdr (cdr calc-curve-coefnames)))
				       calc-curve-varnames))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
216
	     ((memq key '(?x ?X))
217 218 219 220 221 222 223
	      (calc-get-fit-variables calc-curve-nvars 
                                      (1+ calc-curve-nvars) (and homog 0))
	      (setq calc-curve-model (math-mul calc-curve-coefnames
				    (cons 'vec (cons 1 (cdr calc-curve-varnames)))))
	      (setq calc-curve-model (if (eq key ?x)
			      (list 'calcFunc-exp calc-curve-model)
			    (list '^ 10 calc-curve-model))))
Eli Zaretskii's avatar
Eli Zaretskii committed
224
	     ((memq key '(?l ?L))
225 226 227
	      (calc-get-fit-variables calc-curve-nvars 
                                      (1+ calc-curve-nvars) (and homog 0))
	      (setq calc-curve-model (math-mul calc-curve-coefnames
Eli Zaretskii's avatar
Eli Zaretskii committed
228 229 230 231 232 233
				    (cons 'vec
					  (cons 1 (cdr (calcFunc-map
							(if (eq key ?l)
							    '(var ln var-ln)
							  '(var log10
								var-log10))
234
							calc-curve-varnames)))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
235
	     ((= key ?q)
236 237 238 239 240
	      (calc-get-fit-variables calc-curve-nvars 
                                      (1+ (* 2 calc-curve-nvars)) (and homog 0))
	      (let ((c calc-curve-coefnames)
		    (v calc-curve-varnames))
		(setq calc-curve-model (nth 1 c))
Eli Zaretskii's avatar
Eli Zaretskii committed
241
		(while (setq v (cdr v) c (cdr (cdr c)))
242 243
		  (setq calc-curve-model (math-add
			       calc-curve-model
Eli Zaretskii's avatar
Eli Zaretskii committed
244 245 246 247 248 249
			       (list '*
				     (car c)
				     (list '^
					   (list '- (car v) (nth 1 c))
					   2)))))))
	     ((= key ?g)
250 251 252 253
	      (setq calc-curve-model 
                    (math-read-expr "(AFit / BFit sqrt(2 pi)) exp(-0.5 * ((XFit - CFit) / BFit)^2)")
		    calc-curve-varnames '(vec (var XFit var-XFit))
		    calc-curve-coefnames '(vec (var AFit var-AFit)
Eli Zaretskii's avatar
Eli Zaretskii committed
254 255
				    (var BFit var-BFit)
				    (var CFit var-CFit)))
256 257
	      (calc-get-fit-variables 1 (1- (length calc-curve-coefnames)) 
                                      (and homog 1)))
Eli Zaretskii's avatar
Eli Zaretskii committed
258 259 260 261 262 263 264
	     ((memq key '(?\$ ?\' ?u ?U))
	      (let* ((defvars nil)
		     (record-entry nil))
		(if (eq key ?\')
		    (let* ((calc-dollar-values calc-arg-values)
			   (calc-dollar-used 0)
			   (calc-hashes-used 0))
265 266
		      (setq calc-curve-model (calc-do-alg-entry "" "Model formula: "
                                                        nil 'calc-curve-fit-history))
267
		      (if (/= (length calc-curve-model) 1)
Eli Zaretskii's avatar
Eli Zaretskii committed
268
			  (error "Bad format"))
269
		      (setq calc-curve-model (car calc-curve-model)
Eli Zaretskii's avatar
Eli Zaretskii committed
270 271
			    record-entry t)
		      (if (> calc-dollar-used 0)
272
			  (setq calc-curve-coefnames
Eli Zaretskii's avatar
Eli Zaretskii committed
273 274 275 276 277
				(cons 'vec
				      (nthcdr (- (length calc-arg-values)
						 calc-dollar-used)
					      (reverse calc-arg-values))))
			(if (> calc-hashes-used 0)
278
			    (setq calc-curve-coefnames
Eli Zaretskii's avatar
Eli Zaretskii committed
279 280 281
				  (cons 'vec (calc-invent-args
					      calc-hashes-used))))))
		  (progn
282
		    (setq calc-curve-model (cond ((eq key ?u)
Eli Zaretskii's avatar
Eli Zaretskii committed
283 284 285 286
				       (calc-var-value 'var-Model1))
				      ((eq key ?U)
				       (calc-var-value 'var-Model2))
				      (t (calc-top 1))))
287 288 289 290 291 292 293 294 295 296 297 298 299 300
		    (or calc-curve-model (error "User model not yet defined"))
		    (if (math-vectorp calc-curve-model)
			(if (and (memq (length calc-curve-model) '(3 4))
				 (not (math-objvecp (nth 1 calc-curve-model)))
				 (math-vectorp (nth 2 calc-curve-model))
				 (or (null (nth 3 calc-curve-model))
				     (math-vectorp (nth 3 calc-curve-model))))
			    (setq calc-curve-varnames (nth 2 calc-curve-model)
				  calc-curve-coefnames 
                                  (or (nth 3 calc-curve-model)
                                      (cons 'vec
                                            (math-all-vars-but
                                             calc-curve-model calc-curve-varnames)))
				  calc-curve-model (nth 1 calc-curve-model))
Eli Zaretskii's avatar
Eli Zaretskii committed
301
			  (error "Incorrect model specifier")))))
302 303 304 305 306 307 308 309 310 311
		(or calc-curve-varnames
		    (let ((with-y (eq (car-safe calc-curve-model) 'calcFunc-eq)))
		      (if calc-curve-coefnames
			  (calc-get-fit-variables 
                           (if with-y (1+ calc-curve-nvars) calc-curve-nvars)
                           (1- (length calc-curve-coefnames))
                           (math-all-vars-but
                            calc-curve-model calc-curve-coefnames)
                           nil with-y)
			(let* ((coefs (math-all-vars-but calc-curve-model nil))
Eli Zaretskii's avatar
Eli Zaretskii committed
312
			       (vars nil)
313
			       (n (- (length coefs) calc-curve-nvars (if with-y 2 1)))
Eli Zaretskii's avatar
Eli Zaretskii committed
314 315 316 317 318 319
			       p)
			  (if (< n 0)
			      (error "Not enough variables in model"))
			  (setq p (nthcdr n coefs))
			  (setq vars (cdr p))
			  (setcdr p nil)
320 321 322 323
			  (calc-get-fit-variables 
                           (if with-y (1+ calc-curve-nvars) calc-curve-nvars)
                           (length coefs)
                           vars coefs with-y)))))
Eli Zaretskii's avatar
Eli Zaretskii committed
324
		(if record-entry
325 326
		    (calc-record (list 'vec calc-curve-model 
                                       calc-curve-varnames calc-curve-coefnames)
Eli Zaretskii's avatar
Eli Zaretskii committed
327 328 329 330
				 "modl"))))
	     (t (beep))))
     (let ((calc-fit-to-trail t))
       (calc-enter-result n (substring (symbol-name func) 9)
331 332 333 334 335 336 337
			  (list func calc-curve-model
				(if (= (length calc-curve-varnames) 2)
				    (nth 1 calc-curve-varnames)
				  calc-curve-varnames)
				(if (= (length calc-curve-coefnames) 2)
				    (nth 1 calc-curve-coefnames)
				  calc-curve-coefnames)
Eli Zaretskii's avatar
Eli Zaretskii committed
338 339
				data))
       (if (consp calc-fit-to-trail)
340
	   (calc-record (calc-normalize calc-fit-to-trail) "parm"))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
341 342

(defun calc-invent-independent-variables (n &optional but)
343
  (calc-invent-variables n but '(x y z t) "x"))
Eli Zaretskii's avatar
Eli Zaretskii committed
344 345

(defun calc-invent-parameter-variables (n &optional but)
346
  (calc-invent-variables n but '(a b c d) "a"))
Eli Zaretskii's avatar
Eli Zaretskii committed
347 348 349 350 351 352 353 354

(defun calc-invent-variables (num but names base)
  (let ((vars nil)
	(n num) (nn 0)
	var)
    (while (and (> n 0) names)
      (setq var (math-build-var-name (if (consp names)
					 (car names)
355 356
				       (concat base (int-to-string
						     (setq nn (1+ nn)))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
357 358 359 360 361 362
      (or (math-expr-contains (cons 'vec but) var)
	  (setq vars (cons var vars)
		n (1- n)))
      (or (symbolp names) (setq names (cdr names))))
    (if (= n 0)
	(nreverse vars)
363
      (calc-invent-variables num but t base))))
Eli Zaretskii's avatar
Eli Zaretskii committed
364 365

(defun calc-get-fit-variables (nv nc &optional defv defc with-y homog)
366
  (or (= nv (if with-y (1+ calc-curve-nvars) calc-curve-nvars))
Eli Zaretskii's avatar
Eli Zaretskii committed
367 368 369 370 371 372 373 374 375 376
      (error "Wrong number of data vectors for this type of model"))
  (if (integerp defv)
      (setq homog defv
	    defv nil))
  (if homog
      (setq nc (1- nc)))
  (or defv
      (setq defv (calc-invent-independent-variables nv)))
  (or defc
      (setq defc (calc-invent-parameter-variables nc defv)))
377
  (let ((vars (read-string (format "Fitting variables (default %s; %s): "
Eli Zaretskii's avatar
Eli Zaretskii committed
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
				   (mapconcat 'symbol-name
					      (mapcar (function (lambda (v)
								  (nth 1 v)))
						      defv)
					      ",")
				   (mapconcat 'symbol-name
					      (mapcar (function (lambda (v)
								  (nth 1 v)))
						      defc)
					      ","))))
	(coefs nil))
    (setq vars (if (string-match "\\[" vars)
		   (math-read-expr vars)
		 (math-read-expr (concat "[" vars "]"))))
    (if (eq (car-safe vars) 'error)
	(error "Bad format in expression: %s" (nth 2 vars)))
    (or (math-vectorp vars)
	(error "Expected a variable or vector of variables"))
    (if (equal vars '(vec))
	(setq vars (cons 'vec defv)
	      coefs (cons 'vec defc))
      (if (math-vectorp (nth 1 vars))
	  (if (and (= (length vars) 3)
		   (math-vectorp (nth 2 vars)))
	      (setq coefs (nth 2 vars)
		    vars (nth 1 vars))
	    (error
	     "Expected independent variables vector, then parameters vector"))
	(setq coefs (cons 'vec defc))))
    (or (= nv (1- (length vars)))
	(and (not with-y) (= (1+ nv) (1- (length vars))))
	(error "Expected %d independent variable%s" nv (if (= nv 1) "" "s")))
    (or (= nc (1- (length coefs)))
	(error "Expected %d parameter variable%s" nc (if (= nc 1) "" "s")))
    (if homog
	(setq coefs (cons 'vec (cons homog (cdr coefs)))))
414 415 416 417 418 419
    (if calc-curve-varnames
	(setq calc-curve-model (math-multi-subst calc-curve-model (cdr calc-curve-varnames) (cdr vars))))
    (if calc-curve-coefnames
	(setq calc-curve-model (math-multi-subst calc-curve-model (cdr calc-curve-coefnames) (cdr coefs))))
    (setq calc-curve-varnames vars
	  calc-curve-coefnames coefs)))
Eli Zaretskii's avatar
Eli Zaretskii committed
420 421 422 423 424 425 426




;;; The following algorithms are from Numerical Recipes chapter 9.

;;; "rtnewt" with safety kludges
427 428 429

(defvar var-DUMMY)

Eli Zaretskii's avatar
Eli Zaretskii committed
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
(defun math-newton-root (expr deriv guess orig-guess limit)
  (math-working "newton" guess)
  (let* ((var-DUMMY guess)
	 next dval)
    (setq next (math-evaluate-expr expr)
	  dval (math-evaluate-expr deriv))
    (if (and (Math-numberp next)
	     (Math-numberp dval)
	     (not (Math-zerop dval)))
	(progn
	  (setq next (math-sub guess (math-div next dval)))
	  (if (math-nearly-equal guess (setq next (math-float next)))
	      (progn
		(setq var-DUMMY next)
		(list 'vec next (math-evaluate-expr expr)))
	    (if (Math-lessp (math-abs-approx (math-sub next orig-guess))
			    limit)
		(math-newton-root expr deriv next orig-guess limit)
	      (math-reject-arg next "*Newton's method failed to converge"))))
449
      (math-reject-arg next "*Newton's method encountered a singularity"))))
Eli Zaretskii's avatar
Eli Zaretskii committed
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519

;;; Inspired by "rtsafe"
(defun math-newton-search-root (expr deriv guess vguess ostep oostep
				     low vlow high vhigh)
  (let ((var-DUMMY guess)
	(better t)
	pos step next vnext)
    (if guess
	(math-working "newton" (list 'intv 0 low high))
      (math-working "bisect" (list 'intv 0 low high))
      (setq ostep (math-mul-float (math-sub-float high low)
				  '(float 5 -1))
	    guess (math-add-float low ostep)
	    var-DUMMY guess
	    vguess (math-evaluate-expr expr))
      (or (Math-realp vguess)
	  (progn
	    (setq ostep (math-mul-float ostep '(float 6 -1))
		  guess (math-add-float low ostep)
		  var-DUMMY guess
		  vguess (math-evaluate-expr expr))
	    (or (math-realp vguess)
		(progn
		  (setq ostep (math-mul-float ostep '(float 123456 -5))
			guess (math-add-float low ostep)
			var-DUMMY guess
			vguess nil))))))
    (or vguess
	(setq vguess (math-evaluate-expr expr)))
    (or (Math-realp vguess)
	(math-reject-arg guess "*Newton's method encountered a singularity"))
    (setq vguess (math-float vguess))
    (if (eq (Math-negp vlow) (setq pos (Math-posp vguess)))
	(setq high guess
	      vhigh vguess)
      (if (eq (Math-negp vhigh) pos)
	  (setq low guess
		vlow vguess)
	(setq better nil)))
    (if (or (Math-zerop vguess)
	    (math-nearly-equal low high))
	(list 'vec guess vguess)
      (setq step (math-evaluate-expr deriv))
      (if (and (Math-realp step)
	       (not (Math-zerop step))
	       (setq step (math-div-float vguess (math-float step))
		     next (math-sub-float guess step))
	       (not (math-lessp-float high next))
	       (not (math-lessp-float next low)))
	  (progn
	    (setq var-DUMMY next
		  vnext (math-evaluate-expr expr))
	    (if (or (Math-zerop vnext)
		    (math-nearly-equal next guess))
		(list 'vec next vnext)
	      (if (and better
		       (math-lessp-float (math-abs (or oostep
						       (math-sub-float
							high low)))
					 (math-abs
					  (math-mul-float '(float 2 0)
							  step))))
		  (math-newton-search-root expr deriv nil nil nil ostep
					   low vlow high vhigh)
		(math-newton-search-root expr deriv next vnext step ostep
					 low vlow high vhigh))))
	(if (or (and (Math-posp vlow) (Math-posp vhigh))
		(and (Math-negp vlow) (Math-negp vhigh)))
	    (math-search-root expr deriv low vlow high vhigh)
	  (math-newton-search-root expr deriv nil nil nil ostep
520
				   low vlow high vhigh))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
521 522

;;; Search for a root in an interval with no overt zero crossing.
523 524 525 526 527 528

;; The variable math-root-widen is local to math-find-root, but
;; is used by math-search-root, which is called (directly and
;; indirectly) by math-find-root.
(defvar math-root-widen)

Eli Zaretskii's avatar
Eli Zaretskii committed
529 530
(defun math-search-root (expr deriv low vlow high vhigh)
  (let (found)
531
    (if math-root-widen
Eli Zaretskii's avatar
Eli Zaretskii committed
532
	(let ((iters 0)
533
	      (iterlim (if (eq math-root-widen 'point)
Eli Zaretskii's avatar
Eli Zaretskii committed
534 535
			   (+ calc-internal-prec 10)
			 20))
536
	      (factor (if (eq math-root-widen 'point)
Eli Zaretskii's avatar
Eli Zaretskii committed
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
			  '(float 9 0)
			'(float 16 -1)))
	      (prev nil) vprev waslow
	      diff)
	  (while (or (and (math-posp vlow) (math-posp vhigh))
		     (and (math-negp vlow) (math-negp vhigh)))
	    (math-working "widen" (list 'intv 0 low high))
	    (if (> (setq iters (1+ iters)) iterlim)
		(math-reject-arg (list 'intv 0 low high)
				 "*Unable to bracket root"))
	    (if (= iters calc-internal-prec)
		(setq factor '(float 16 -1)))
	    (setq diff (math-mul-float (math-sub-float high low) factor))
	    (if (Math-zerop diff)
		(setq high (calcFunc-incr high 10))
	      (if (math-lessp-float (math-abs vlow) (math-abs vhigh))
		  (setq waslow t
			prev low
			low (math-sub low diff)
			var-DUMMY low
			vprev vlow
			vlow (math-evaluate-expr expr))
		(setq waslow nil
		      prev high
		      high (math-add high diff)
		      var-DUMMY high
		      vprev vhigh
		      vhigh (math-evaluate-expr expr)))))
	  (if prev
	      (if waslow
		  (setq high prev vhigh vprev)
		(setq low prev vlow vprev)))
	  (setq found t))
      (or (Math-realp vlow)
	  (math-reject-arg vlow 'realp))
      (or (Math-realp vhigh)
	  (math-reject-arg vhigh 'realp))
      (let ((xvals (list low high))
	    (yvals (list vlow vhigh))
	    (pos (Math-posp vlow))
	    (levels 0)
	    (step (math-sub-float high low))
	    xp yp var-DUMMY)
	(while (and (<= (setq levels (1+ levels)) 5)
		    (not found))
	  (setq xp xvals
		yp yvals
		step (math-mul-float step '(float 497 -3)))
	  (while (and (cdr xp) (not found))
	    (if (Math-realp (car yp))
		(setq low (car xp)
		      vlow (car yp)))
	    (setq high (math-add-float (car xp) step)
		  var-DUMMY high
		  vhigh (math-evaluate-expr expr))
	    (math-working "search" high)
	    (if (and (Math-realp vhigh)
		     (eq (math-negp vhigh) pos))
		(setq found t)
	      (setcdr xp (cons high (cdr xp)))
	      (setcdr yp (cons vhigh (cdr yp)))
	      (setq xp (cdr (cdr xp))
		    yp (cdr (cdr yp))))))))
    (if found
	(if (Math-zerop vhigh)
	    (list 'vec high vhigh)
	  (if (Math-zerop vlow)
	      (list 'vec low vlow)
	    (if deriv
		(math-newton-search-root expr deriv nil nil nil nil
					 low vlow high vhigh)
	      (math-bisect-root expr low vlow high vhigh))))
      (math-reject-arg (list 'intv 3 low high)
610
		       "*Unable to find a sign change in this interval"))))
Eli Zaretskii's avatar
Eli Zaretskii committed
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631

;;; "rtbis"  (but we should be using Brent's method)
(defun math-bisect-root (expr low vlow high vhigh)
  (let ((step (math-sub-float high low))
	(pos (Math-posp vhigh))
	var-DUMMY
	mid vmid)
    (while (not (or (math-nearly-equal low
				       (setq step (math-mul-float
						   step '(float 5 -1))
					     mid (math-add-float low step)))
		    (progn
		      (setq var-DUMMY mid
			    vmid (math-evaluate-expr expr))
		      (Math-zerop vmid))))
      (math-working "bisect" mid)
      (if (eq (Math-posp vmid) pos)
	  (setq high mid
		vhigh vmid)
	(setq low mid
	      vlow vmid)))
632
    (list 'vec mid vmid)))
Eli Zaretskii's avatar
Eli Zaretskii committed
633 634

;;; "mnewt"
635 636 637

(defvar math-root-vars [(var DUMMY var-DUMMY)])

Eli Zaretskii's avatar
Eli Zaretskii committed
638 639 640 641 642 643 644 645
(defun math-newton-multi (expr jacob n guess orig-guess limit)
  (let ((m -1)
	(p guess)
	p2 expr-val jacob-val next)
    (while (< (setq p (cdr p) m (1+ m)) n)
      (set (nth 2 (aref math-root-vars m)) (car p)))
    (setq expr-val (math-evaluate-expr expr)
	  jacob-val (math-evaluate-expr jacob))
646 647 648
    (unless (and (math-constp expr-val)
		 (math-constp jacob-val))
      (math-reject-arg guess "*Newton's method encountered a singularity"))
Eli Zaretskii's avatar
Eli Zaretskii committed
649 650 651 652 653 654 655 656 657 658 659
    (setq next (math-add guess (math-div (math-float (math-neg expr-val))
					 (math-float jacob-val)))
	  p guess p2 next)
    (math-working "newton" next)
    (while (and (setq p (cdr p) p2 (cdr p2))
		(math-nearly-equal (car p) (car p2))))
    (if p
	(if (Math-lessp (math-abs-approx (math-sub next orig-guess))
			limit)
	    (math-newton-multi expr jacob n next orig-guess limit)
	  (math-reject-arg nil "*Newton's method failed to converge"))
660
      (list 'vec next expr-val))))
Eli Zaretskii's avatar
Eli Zaretskii committed
661 662


663
(defun math-find-root (expr var guess math-root-widen)
Eli Zaretskii's avatar
Eli Zaretskii committed
664 665 666 667 668 669
  (if (eq (car-safe expr) 'vec)
      (let ((n (1- (length expr)))
	    (calc-symbolic-mode nil)
	    (var-DUMMY nil)
	    (jacob (list 'vec))
	    p p2 m row)
670 671 672 673
	(unless (eq (car-safe var) 'vec)
	  (math-reject-arg var 'vectorp))
	(unless (= (length var) (1+ n))
	  (math-dimension-error))
Eli Zaretskii's avatar
Eli Zaretskii committed
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
	(setq expr (copy-sequence expr))
	(while (>= n (length math-root-vars))
	  (let ((symb (intern (concat "math-root-v"
				      (int-to-string
				       (length math-root-vars))))))
	    (setq math-root-vars (vconcat math-root-vars
					  (vector (list 'var symb symb))))))
	(setq m -1)
	(while (< (setq m (1+ m)) n)
	  (set (nth 2 (aref math-root-vars m)) nil))
	(setq m -1 p var)
	(while (setq m (1+ m) p (cdr p))
	  (or (eq (car-safe (car p)) 'var)
	      (math-reject-arg var "*Expected a variable"))
	  (setq p2 expr)
	  (while (setq p2 (cdr p2))
	    (setcar p2 (math-expr-subst (car p2) (car p)
					(aref math-root-vars m)))))
692 693 694 695
	(unless (eq (car-safe guess) 'vec)
	  (math-reject-arg guess 'vectorp))
	(unless (= (length guess) (1+ n))
	  (math-dimension-error))
Eli Zaretskii's avatar
Eli Zaretskii committed
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
	(setq guess (copy-sequence guess)
	      p guess)
	(while (setq p (cdr p))
	  (or (Math-numberp (car guess))
	      (math-reject-arg guess 'numberp))
	  (setcar p (math-float (car p))))
	(setq p expr)
	(while (setq p (cdr p))
	  (if (assq (car-safe (car p)) calc-tweak-eqn-table)
	      (setcar p (math-sub (nth 1 (car p)) (nth 2 (car p)))))
	  (setcar p (math-evaluate-expr (car p)))
	  (setq row (list 'vec)
		m -1)
	  (while (< (setq m (1+ m)) n)
	    (nconc row (list (math-evaluate-expr
			      (or (calcFunc-deriv (car p)
						  (aref math-root-vars m)
						  nil t)
				  (math-reject-arg
				   expr
				   "*Formulas must be differentiable"))))))
	  (nconc jacob (list row)))
	(setq m (math-abs-approx guess))
	(math-newton-multi expr jacob n guess guess
			   (if (math-zerop m) '(float 1 3) (math-mul m 10))))
721 722 723 724
    (unless (eq (car-safe var) 'var)
      (math-reject-arg var "*Expected a variable"))
    (unless (math-expr-contains expr var)
      (math-reject-arg expr "*Formula does not contain specified variable"))
Eli Zaretskii's avatar
Eli Zaretskii committed
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
    (if (assq (car expr) calc-tweak-eqn-table)
	(setq expr (math-sub (nth 1 expr) (nth 2 expr))))
    (math-with-extra-prec 2
      (setq expr (math-expr-subst expr var '(var DUMMY var-DUMMY)))
      (let* ((calc-symbolic-mode nil)
	     (var-DUMMY nil)
	     (expr (math-evaluate-expr expr))
	     (deriv (calcFunc-deriv expr '(var DUMMY var-DUMMY) nil t))
	     low high vlow vhigh)
	(and deriv (setq deriv (math-evaluate-expr deriv)))
	(setq guess (math-float guess))
	(if (and (math-numberp guess)
		 deriv)
	    (math-newton-root expr deriv guess guess
			      (if (math-zerop guess) '(float 1 6)
				(math-mul (math-abs-approx guess) 100)))
	  (if (Math-realp guess)
	      (setq low guess
		    high guess
		    var-DUMMY guess
		    vlow (math-evaluate-expr expr)
		    vhigh vlow
747
		    math-root-widen 'point)
Eli Zaretskii's avatar
Eli Zaretskii committed
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
	    (if (eq (car guess) 'intv)
		(progn
		  (or (math-constp guess) (math-reject-arg guess 'constp))
		  (setq low (nth 2 guess)
			high (nth 3 guess))
		  (if (memq (nth 1 guess) '(0 1))
		      (setq low (calcFunc-incr low 1 high)))
		  (if (memq (nth 1 guess) '(0 2))
		      (setq high (calcFunc-incr high -1 low)))
		  (setq var-DUMMY low
			vlow (math-evaluate-expr expr)
			var-DUMMY high
			vhigh (math-evaluate-expr expr)))
	      (if (math-complexp guess)
		  (math-reject-arg "*Complex root finder must have derivative")
		(math-reject-arg guess 'realp))))
	  (if (Math-zerop vlow)
	      (list 'vec low vlow)
	    (if (Math-zerop vhigh)
		(list 'vec high vhigh)
	      (if (and deriv (Math-numberp vlow) (Math-numberp vhigh))
		  (math-newton-search-root expr deriv nil nil nil nil
					   low vlow high vhigh)
		(if (or (and (Math-posp vlow) (Math-posp vhigh))
			(and (Math-negp vlow) (Math-negp vhigh))
			(not (Math-numberp vlow))
			(not (Math-numberp vhigh)))
		    (math-search-root expr deriv low vlow high vhigh)
776
		  (math-bisect-root expr low vlow high vhigh))))))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
777 778

(defun calcFunc-root (expr var guess)
779
  (math-find-root expr var guess nil))
Eli Zaretskii's avatar
Eli Zaretskii committed
780 781

(defun calcFunc-wroot (expr var guess)
782
  (math-find-root expr var guess t))
Eli Zaretskii's avatar
Eli Zaretskii committed
783 784 785 786 787 788




;;; The following algorithms come from Numerical Recipes, chapter 10.

789 790
(defvar math-min-vars [(var DUMMY var-DUMMY)])

Eli Zaretskii's avatar
Eli Zaretskii committed
791 792 793 794 795 796 797 798 799 800 801
(defun math-min-eval (expr a)
  (if (Math-vectorp a)
      (let ((m -1))
	(while (setq m (1+ m) a (cdr a))
	  (set (nth 2 (aref math-min-vars m)) (car a))))
    (setq var-DUMMY a))
  (setq a (math-evaluate-expr expr))
  (if (Math-ratp a)
      (math-float a)
    (if (eq (car a) 'float)
	a
802
      (math-reject-arg a 'realp))))
Eli Zaretskii's avatar
Eli Zaretskii committed
803

804
(defvar math-min-or-max "minimum")
Eli Zaretskii's avatar
Eli Zaretskii committed
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870

;;; A bracket for a minimum is a < b < c where f(b) < f(a) and f(b) < f(c).

;;; "mnbrak"
(defun math-widen-min (expr a b)
  (let ((done nil)
	(iters 30)
	incr c va vb vc u vu r q ulim bc ba qr)
    (or b (setq b (math-mul a '(float 101 -2))))
    (setq va (math-min-eval expr a)
	  vb (math-min-eval expr b))
    (if (math-lessp-float va vb)
	(setq u a a b b u
	      vu va va vb vb vu))
    (setq c (math-add-float b (math-mul-float '(float 161803 -5)
					      (math-sub-float b a)))
	  vc (math-min-eval expr c))
    (while (and (not done) (math-lessp-float vc vb))
      (math-working "widen" (list 'intv 0 a c))
      (if (= (setq iters (1- iters)) 0)
	  (math-reject-arg nil (format "*Unable to find a %s near the interval"
				       math-min-or-max)))
      (setq bc (math-sub-float b c)
	    ba (math-sub-float b a)
	    r (math-mul-float ba (math-sub-float vb vc))
	    q (math-mul-float bc (math-sub-float vb va))
	    qr (math-sub-float q r))
      (if (math-lessp-float (math-abs qr) '(float 1 -20))
	  (setq qr (if (math-negp qr) '(float -1 -20) '(float 1 -20))))
      (setq u (math-sub-float
	       b
	       (math-div-float (math-sub-float (math-mul-float bc q)
					       (math-mul-float ba r))
			       (math-mul-float '(float 2 0) qr)))
	    ulim (math-add-float b (math-mul-float '(float -1 2) bc))
	    incr (math-negp bc))
      (if (if incr (math-lessp-float b u) (math-lessp-float u b))
	  (if (if incr (math-lessp-float u c) (math-lessp-float c u))
	      (if (math-lessp-float (setq vu (math-min-eval expr u)) vc)
		  (setq a b  va vb
			b u  vb vu
			done t)
		(if (math-lessp-float vb vu)
		    (setq c u  vc vu
			  done t)
		  (setq u (math-add-float c (math-mul-float '(float -161803 -5)
							    bc))
			vu (math-min-eval expr u))))
	    (if (if incr (math-lessp-float u ulim) (math-lessp-float ulim u))
		(if (math-lessp-float (setq vu (math-min-eval expr u)) vc)
		    (setq b c  vb vc
			  c u  vc vu
			  u (math-add-float c (math-mul-float
					       '(float -161803 -5)
					       (math-sub-float b c)))
			  vu (math-min-eval expr u)))
	      (setq u ulim
		    vu (math-min-eval expr u))))
	(setq u (math-add-float c (math-mul-float '(float -161803 -5)
						  bc))
	      vu (math-min-eval expr u)))
      (setq a b  va vb
	    b c  vb vc
	    c u  vc vu))
    (if (math-lessp-float a c)
	(list a va b vb c vc)
871
      (list c vc b vb a va))))
Eli Zaretskii's avatar
Eli Zaretskii committed
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920

(defun math-narrow-min (expr a c intv)
  (let ((xvals (list a c))
	(yvals (list (math-min-eval expr a)
		     (math-min-eval expr c)))
	(levels 0)
	(step (math-sub-float c a))
	(found nil)
	xp yp b)
    (while (and (<= (setq levels (1+ levels)) 5)
		(not found))
      (setq xp xvals
	    yp yvals
	    step (math-mul-float step '(float 497 -3)))
      (while (and (cdr xp) (not found))
	(setq b (math-add-float (car xp) step))
	(math-working "search" b)
	(setcdr xp (cons b (cdr xp)))
	(setcdr yp (cons (math-min-eval expr b) (cdr yp)))
	(if (and (math-lessp-float (nth 1 yp) (car yp))
		 (math-lessp-float (nth 1 yp) (nth 2 yp)))
	    (setq found t)
	  (setq xp (cdr xp)
		yp (cdr yp))
	  (if (and (cdr (cdr yp))
		   (math-lessp-float (nth 1 yp) (car yp))
		   (math-lessp-float (nth 1 yp) (nth 2 yp)))
	      (setq found t)
	    (setq xp (cdr xp)
		  yp (cdr yp))))))
    (if found
	(list (car xp) (car yp)
	      (nth 1 xp) (nth 1 yp)
	      (nth 2 xp) (nth 2 yp))
      (or (if (math-lessp-float (car yvals) (nth 1 yvals))
	      (and (memq (nth 1 intv) '(2 3))
		   (let ((min (car yvals)))
		     (while (and (setq yvals (cdr yvals))
				 (math-lessp-float min (car yvals))))
		     (and (not yvals)
			  (list (nth 2 intv) min))))
	    (and (memq (nth 1 intv) '(1 3))
		 (setq yvals (nreverse yvals))
		 (let ((min (car yvals)))
		   (while (and (setq yvals (cdr yvals))
			       (math-lessp-float min (car yvals))))
		   (and (not yvals)
			(list (nth 3 intv) min)))))
	  (math-reject-arg nil (format "*Unable to find a %s in the interval"
921
				       math-min-or-max))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
922 923 924 925 926 927 928 929 930 931 932

;;; "brent"
(defun math-brent-min (expr prec a va x vx b vb)
  (let ((iters (+ 20 (* 5 prec)))
	(w x)
	(vw vx)
	(v x)
	(vv vx)
	(tol (list 'float 1 (- -1 prec)))
	(zeps (list 'float 1 (- -5 prec)))
	(e '(float 0 0))
933
	d u vu xm tol1 tol2 etemp p q r xv xw)
Eli Zaretskii's avatar
Eli Zaretskii committed
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
    (while (progn
	     (setq xm (math-mul-float '(float 5 -1)
				      (math-add-float a b))
		   tol1 (math-add-float
			 zeps
			 (math-mul-float tol (math-abs x)))
		   tol2 (math-mul-float tol1 '(float 2 0)))
	     (math-lessp-float (math-sub-float tol2
					       (math-mul-float
						'(float 5 -1)
						(math-sub-float b a)))
			       (math-abs (math-sub-float x xm))))
      (if (= (setq iters (1- iters)) 0)
	  (math-reject-arg nil (format "*Unable to converge on a %s"
				       math-min-or-max)))
      (math-working "brent" x)
      (if (math-lessp-float (math-abs e) tol1)
	  (setq e (if (math-lessp-float x xm)
		      (math-sub-float b x)
		    (math-sub-float a x))
		d (math-mul-float '(float 381966 -6) e))
	(setq xw (math-sub-float x w)
	      r (math-mul-float xw (math-sub-float vx vv))
	      xv (math-sub-float x v)
	      q (math-mul-float xv (math-sub-float vx vw))
	      p (math-sub-float (math-mul-float xv q)
				(math-mul-float xw r))
	      q (math-mul-float '(float 2 0) (math-sub-float q r)))
	(if (math-posp q)
	    (setq p (math-neg-float p))
	  (setq q (math-neg-float q)))
	(setq etemp e
	      e d)
	(if (and (math-lessp-float (math-abs p)
				   (math-abs (math-mul-float
					      '(float 5 -1)
					      (math-mul-float q etemp))))
		 (math-lessp-float (math-mul-float
				    q (math-sub-float a x)) p)
		 (math-lessp-float p (math-mul-float
				      q (math-sub-float b x))))
	    (progn
	      (setq d (math-div-float p q)
		    u (math-add-float x d))
	      (if (or (math-lessp-float (math-sub-float u a) tol2)
		      (math-lessp-float (math-sub-float b u) tol2))
		  (setq d (if (math-lessp-float xm x)
			      (math-neg-float tol1)
			    tol1))))
	  (setq e (if (math-lessp-float x xm)
		      (math-sub-float b x)
		    (math-sub-float a x))
		d (math-mul-float '(float 381966 -6) e))))
      (setq u (math-add-float x
			      (if (math-lessp-float (math-abs d) tol1)
				  (if (math-negp d)
				      (math-neg-float tol1)
				    tol1)
				d))
	    vu (math-min-eval expr u))
      (if (math-lessp-float vx vu)
	  (progn
	    (if (math-lessp-float u x)
		(setq a u)
	      (setq b u))
	    (if (or (equal w x)
		    (not (math-lessp-float vw vu)))
		(setq v w  vv vw
		      w u  vw vu)
	      (if (or (equal v x)
		      (equal v w)
		      (not (math-lessp-float vv vu)))
		  (setq v u  vv vu))))
	(if (math-lessp-float u x)
	    (setq b x)
	  (setq a x))
	(setq v w  vv vw
	      w x  vw vx
	      x u  vx vu)))
1013
    (list 'vec x vx)))
Eli Zaretskii's avatar
Eli Zaretskii committed
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072

;;; "powell"
(defun math-powell-min (expr n guesses prec)
  (let* ((f1dim (math-line-min-func expr n))
	 (xi (calcFunc-idn 1 n))
	 (p (cons 'vec (mapcar 'car guesses)))
	 (pt p)
	 (ftol (list 'float 1 (- prec)))
	 (fret (math-min-eval expr p))
	 fp ptt fptt xit i ibig del diff res)
    (while (progn
	     (setq fp fret
		   ibig 0
		   del '(float 0 0)
		   i 0)
	     (while (<= (setq i (1+ i)) n)
	       (setq fptt fret
		     res (math-line-min f1dim p
					(math-mat-col xi i)
					n prec)
		     p (let ((calc-internal-prec prec))
			 (math-normalize (car res)))
		     fret (nth 2 res)
		     diff (math-abs (math-sub-float fptt fret)))
	       (if (math-lessp-float del diff)
		   (setq del diff
			 ibig i)))
	     (math-lessp-float
	      (math-mul-float ftol
			      (math-add-float (math-abs fp)
					      (math-abs fret)))
	      (math-mul-float '(float 2 0)
			      (math-abs (math-sub-float fp
							fret)))))
      (setq ptt (math-sub (math-mul '(float 2 0) p) pt)
	    xit (math-sub p pt)
	    pt p
	    fptt (math-min-eval expr ptt))
      (if (and (math-lessp-float fptt fp)
	       (math-lessp-float
		(math-mul-float
		 (math-mul-float '(float 2 0)
				 (math-add-float
				  (math-sub-float fp
						  (math-mul-float '(float 2 0)
								  fret))
				  fptt))
		 (math-sqr-float (math-sub-float
				  (math-sub-float fp fret) del)))
		(math-mul-float del
				(math-sqr-float (math-sub-float fp fptt)))))
	  (progn
	    (setq res (math-line-min f1dim p xit n prec)
		  p (car res)
		  fret (nth 2 res)
		  i 0)
	    (while (<= (setq i (1+ i)) n)
	      (setcar (nthcdr ibig (nth i xi))
		      (nth i (nth 1 res)))))))
1073
    (list 'vec p fret)))
Eli Zaretskii's avatar
Eli Zaretskii committed
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083

(defun math-line-min-func (expr n)
  (let ((m -1))
    (while (< (setq m (1+ m)) n)
      (set (nth 2 (aref math-min-vars m))
	   (list '+
		 (list '*
		       '(var DUMMY var-DUMMY)
		       (list 'calcFunc-mrow '(var line-xi line-xi) (1+ m)))
		 (list 'calcFunc-mrow '(var line-p line-p) (1+ m)))))
1084
    (math-evaluate-expr expr)))
Eli Zaretskii's avatar
Eli Zaretskii committed
1085 1086 1087 1088 1089 1090 1091

(defun math-line-min (f1dim line-p line-xi n prec)
  (let* ((var-DUMMY nil)
	 (expr (math-evaluate-expr f1dim))
	 (params (math-widen-min expr '(float 0 0) '(float 1 0)))
	 (res (apply 'math-brent-min expr prec params))
	 (xi (math-mul (nth 1 res) line-xi)))
1092
    (list (math-add line-p xi) xi (nth 2 res))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108


(defun math-find-minimum (expr var guess min-widen)
  (let* ((calc-symbolic-mode nil)
	 (n 0)
	 (var-DUMMY nil)
	 (isvec (math-vectorp var))
	 g guesses)
    (or (math-vectorp var)
	(setq var (list 'vec var)))
    (or (math-vectorp guess)
	(setq guess (list 'vec guess)))
    (or (= (length var) (length guess))
	(math-dimension-error))
    (while (setq var (cdr var) guess (cdr guess))
      (or (eq (car-safe (car var)) 'var)
1109
	  (math-reject-arg (car var) "*Expected a variable"))
Eli Zaretskii's avatar
Eli Zaretskii committed
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
      (or (math-expr-contains expr (car var))
	  (math-reject-arg (car var)
			   "*Formula does not contain specified variable"))
      (while (>= (1+ n) (length math-min-vars))
	(let ((symb (intern (concat "math-min-v"
				    (int-to-string
				     (length math-min-vars))))))
	  (setq math-min-vars (vconcat math-min-vars
				       (vector (list 'var symb symb))))))
      (set (nth 2 (aref math-min-vars n)) nil)
      (set (nth 2 (aref math-min-vars (1+ n))) nil)
      (if (math-complexp (car guess))
	  (setq expr (math-expr-subst expr
				      (car var)
				      (list '+ (aref math-min-vars n)
					    (list '*
						  (aref math-min-vars (1+ n))
						  '(cplx 0 1))))
		guesses (let ((g (math-float (math-complex (car guess)))))
			  (cons (list (nth 2 g) nil nil)
				(cons (list (nth 1 g) nil nil t)
				      guesses)))
		n (+ n 2))
	(setq expr (math-expr-subst expr
				    (car var)
				    (aref math-min-vars n))
	      guesses (cons (if (math-realp (car guess))
				(list (math-float (car guess)) nil nil)
			      (if (and (eq (car-safe (car guess)) 'intv)
				       (math-constp (car guess)))
				  (list (math-mul
					 (math-add (nth 2 (car guess))
						   (nth 3 (car guess)))
					 '(float 5 -1))
					(math-float (nth 2 (car guess)))
					(math-float (nth 3 (car guess)))
					(car guess))
				(math-reject-arg (car guess) 'realp)))
			    guesses)
	      n (1+ n))))
    (setq guesses (nreverse guesses)
	  expr (math-evaluate-expr expr))
    (if (= n 1)
	(let* ((params (if (nth 1 (car guesses))
			   (if min-widen
			       (math-widen-min expr
					       (nth 1 (car guesses))
					       (nth 2 (car guesses)))
			     (math-narrow-min expr
					      (nth 1 (car guesses))
					      (nth 2 (car guesses))
					      (nth 3 (car guesses))))
			 (math-widen-min expr
					 (car (car guesses))
					 nil)))
	       (prec calc-internal-prec)
	       (res (if (cdr (cdr params))
			(math-with-extra-prec (+ calc-internal-prec 2)
			  (apply 'math-brent-min expr prec params))
		      (cons 'vec params))))
	  (if isvec
	      (list 'vec (list 'vec (nth 1 res)) (nth 2 res))
	    res))
      (let* ((prec calc-internal-prec)
	     (res (math-with-extra-prec (+ calc-internal-prec 2)
		    (math-powell-min expr n guesses prec)))
	     (p (nth 1 res))
	     (vec (list 'vec)))
	(while (setq p (cdr p))
	  (if (nth 3 (car guesses))
	      (progn
		(nconc vec (list (math-normalize
				  (list 'cplx (car p) (nth 1 p)))))
		(setq p (cdr p)
		      guesses (cdr guesses)))
	    (nconc vec (list (car p))))
	  (setq guesses (cdr guesses)))
	(if isvec
	    (list 'vec vec (nth 2 res))
1189
	  (list 'vec (nth 1 vec) (nth 2 res)))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1190 1191 1192 1193 1194 1195

(defun calcFunc-minimize (expr var guess)
  (let ((calc-internal-prec (max (/ calc-internal-prec 2) 3))
	(math-min-or-max "minimum"))
    (math-find-minimum (math-normalize expr)
		       (math-normalize var)
1196
		       (math-normalize guess) nil)))
Eli Zaretskii's avatar
Eli Zaretskii committed
1197 1198 1199 1200 1201 1202

(defun calcFunc-wminimize (expr var guess)
  (let ((calc-internal-prec (max (/ calc-internal-prec 2) 3))
	(math-min-or-max "minimum"))
    (math-find-minimum (math-normalize expr)
		       (math-normalize var)
1203
		       (math-normalize guess) t)))
Eli Zaretskii's avatar
Eli Zaretskii committed
1204 1205 1206 1207 1208 1209 1210

(defun calcFunc-maximize (expr var guess)
  (let* ((calc-internal-prec (max (/ calc-internal-prec 2) 3))
	 (math-min-or-max "maximum")
	 (res (math-find-minimum (math-normalize (math-neg expr))
				 (math-normalize var)
				 (math-normalize guess) nil)))
1211
    (list 'vec (nth 1 res) (math-neg (nth 2 res)))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1212 1213 1214 1215 1216 1217 1218

(defun calcFunc-wmaximize (expr var guess)
  (let* ((calc-internal-prec (max (/ calc-internal-prec 2) 3))
	 (math-min-or-max "maximum")
	 (res (math-find-minimum (math-normalize (math-neg expr))
				 (math-normalize var)
				 (math-normalize guess) t)))
1219
    (list 'vec (nth 1 res) (math-neg (nth 2 res)))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237




;;; The following algorithms come from Numerical Recipes, chapter 3.

(defun calcFunc-polint (data x)
  (or (math-matrixp data) (math-reject-arg data 'matrixp))
  (or (= (length data) 3)
      (math-reject-arg data "*Wrong number of data rows"))
  (or (> (length (nth 1 data)) 2)
      (math-reject-arg data "*Too few data points"))
  (if (and (math-vectorp x) (or (math-constp x) math-expand-formulas))
      (cons 'vec (mapcar (function (lambda (x) (calcFunc-polint data x)))
			 (cdr x)))
    (or (math-objectp x) math-expand-formulas (math-reject-arg x 'objectp))
    (math-with-extra-prec 2
      (cons 'vec (math-poly-interp (cdr (nth 1 data)) (cdr (nth 2 data)) x
1238
				   nil)))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
(put 'calcFunc-polint 'math-expandable t)


(defun calcFunc-ratint (data x)
  (or (math-matrixp data) (math-reject-arg data 'matrixp))
  (or (= (length data) 3)
      (math-reject-arg data "*Wrong number of data rows"))
  (or (> (length (nth 1 data)) 2)
      (math-reject-arg data "*Too few data points"))
  (if (and (math-vectorp x) (or (math-constp x) math-expand-formulas))
      (cons 'vec (mapcar (function (lambda (x) (calcFunc-ratint data x)))
			 (cdr x)))
    (or (math-objectp x) math-expand-formulas (math-reject-arg x 'objectp))
    (math-with-extra-prec 2
      (cons 'vec (math-poly-interp (cdr (nth 1 data)) (cdr (nth 2 data)) x
1254
				   (cdr (cdr (cdr (nth 1 data)))))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
(put 'calcFunc-ratint 'math-expandable t)


(defun math-poly-interp (xa ya x ratp)
  (let ((n (length xa))
	(dif nil)
	(ns nil)
	(xax nil)
	(c (copy-sequence ya))
	(d (copy-sequence ya))
	(i 0)
	(m 0)
	y dy (xp xa) xpm cp dp temp)
    (while (<= (setq i (1+ i)) n)
      (setq xax (cons (math-sub (car xp) x) xax)
	    xp (cdr xp)
	    temp (math-abs (car xax)))
      (if (or (null dif) (math-lessp temp dif))
	  (setq dif temp
		ns i)))
    (setq xax (nreverse xax)
	  ns (1- ns)
	  y (nth ns ya))
    (if (math-zerop dif)
	(list y 0)
      (while (< (setq m (1+ m)) n)
	(setq i 0
	      xp xax
	      xpm (nthcdr m xax)
	      cp c
	      dp d)
	(while (<= (setq i (1+ i)) (- n m))
	  (if ratp
	      (let ((t2 (math-div (math-mul (car xp) (car dp)) (car xpm))))
		(setq temp (math-div (math-sub (nth 1 cp) (car dp))
				     (math-sub t2 (nth 1 cp))))
		(setcar dp (math-mul (nth 1 cp) temp))
		(setcar cp (math-mul t2 temp)))
	    (if (math-equal (car xp) (car xpm))
		(math-reject-arg (cons 'vec xa) "*Duplicate X values"))
	    (setq temp (math-div (math-sub (nth 1 cp) (car dp))
				 (math-sub (car xp) (car xpm))))
	    (setcar dp (math-mul (car xpm) temp))
	    (setcar cp (math-mul (car xp) temp)))
	  (setq cp (cdr cp)
		dp (cdr dp)
		xp (cdr xp)
		xpm (cdr xpm)))
	(if (< (+ ns ns) (- n m))
	    (setq dy (nth ns c))
	  (setq ns (1- ns)
		dy (nth ns d)))
	(setq y (math-add y dy)))
1308
      (list y dy))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346



;;; The following algorithms come from Numerical Recipes, chapter 4.

(defun calcFunc-ninteg (expr var lo hi)
  (setq lo (math-evaluate-expr lo)
	hi (math-evaluate-expr hi))
  (or (math-numberp lo) (math-infinitep lo) (math-reject-arg lo 'numberp))
  (or (math-numberp hi) (math-infinitep hi) (math-reject-arg hi 'numberp))
  (if (math-lessp hi lo)
      (math-neg (calcFunc-ninteg expr var hi lo))
    (setq expr (math-expr-subst expr var '(var DUMMY var-DUMMY)))
    (let ((var-DUMMY nil)
	  (calc-symbolic-mode nil)
	  (calc-prefer-frac nil)
	  (sum 0))
      (setq expr (math-evaluate-expr expr))
      (if (equal lo '(neg (var inf var-inf)))
	  (let ((thi (if (math-lessp hi '(float -2 0))
			 hi '(float -2 0))))
	    (setq sum (math-ninteg-romberg
		       'math-ninteg-midpoint expr
			 (math-float lo) (math-float thi) 'inf)
		  lo thi)))
      (if (equal hi '(var inf var-inf))
	  (let ((tlo (if (math-lessp '(float 2 0) lo)
			 lo '(float 2 0))))
	    (setq sum (math-add sum
				(math-ninteg-romberg
				 'math-ninteg-midpoint expr
				 (math-float tlo) (math-float hi) 'inf))
		  hi tlo)))
      (or (math-equal lo hi)
	  (setq sum (math-add sum
			      (math-ninteg-romberg
			       'math-ninteg-midpoint expr
			       (math-float lo) (math-float hi) nil))))
1347
      sum)))
Eli Zaretskii's avatar
Eli Zaretskii committed
1348 1349 1350


;;; Open Romberg method; "qromo" in section 4.4.
1351 1352 1353 1354 1355 1356

;; The variable math-ninteg-temp is local to math-ninteg-romberg,
;; but is used by math-ninteg-midpoint, which is used by 
;; math-ninteg-romberg.
(defvar math-ninteg-temp)

1357
(defun math-ninteg-romberg (func expr lo hi mode)
Eli Zaretskii's avatar
Eli Zaretskii committed
1358 1359