Fix bug #3996: parse_string fails to parse string which contains semicolon
[maxima.git] / src / algsys.lisp
blobf6bdef041b962c1bbaf5b08ce4cc99dd9373762c
1 ;;; -*- Mode: Lisp; Package: Maxima; Syntax: Common-Lisp; Base: 10 -*- ;;;;
2 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3 ;;; The data in this file contains enhancments. ;;;;;
4 ;;; ;;;;;
5 ;;; Copyright (c) 1984,1987 by William Schelter,University of Texas ;;;;;
6 ;;; All rights reserved ;;;;;
7 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
8 ;;; (c) Copyright 1981 Massachusetts Institute of Technology ;;;
9 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
11 (in-package :maxima)
13 (macsyma-module algsys)
15 (load-macsyma-macros ratmac)
17 ;;This is the algsys package.
19 ;;It solves systems of polynomial equations by straight-forward
20 ;;resultant hackery. Other possible methods seem worse:
21 ;;the Buchberger-Spear canonical ideal basis algorithm is slow,
22 ;;and the "resolvent" method (see van der Waerden, section 79)
23 ;;blows up in time and space. The "resultant"
24 ;;method (see the following sections of van der Waerden and
25 ;;Macaulay's book - Algebraic Theory of Modular Systems) looks
26 ;;good, but it requires the evaluation of large determinants.
27 ;;Unless some hack (such as prs's for evaluating resultants of
28 ;;two polynomials) is developed for multi-polynomial resultants,
29 ;;this method will remain impractical.
31 ;;Some other possible ideas: Keeping the total number of equations constant,
32 ;;in an effort to reduce extraneous solutions, or Reducing to a linear
33 ;;equation before taking resultants.
35 (declare-top (special $algdelta $ratepsilon $algepsilon $keepfloat
36 varlist genvar *roots *failures $ratprint $numer $ratfac
37 $solvefactors $dispflag $breakup
38 *tvarxlist* errorsw $programmode *ivar* errset $polyfactor
39 bindlist loclist $float $infeval))
41 ;;note if $algepsilon is too large you may lose some roots.
43 (defmvar $algdelta 1e-5 )
45 (defmvar $%rnum_list '((mlist))
46 "Upon exit from ALGSYS this is bound to a list of the %RNUMS
47 which where introduced into the expression. Useful for mapping
48 over and using as an argument to SUBST.")
50 (defmvar $realonly nil "If t only real solutions are returned.")
52 (defmvar realonlyratnum nil
53 "A REALROOTS hack for RWG. Causes ALGSYS to retain rational numbers
54 returned by REALROOTS when REALONLY is TRUE."
55 in-core)
57 (defmvar $algexact nil "If t ALGSYS always calls SOLVE to try to MAXIMA-FIND exact
58 solutions.")
60 (defmvar algnotexact nil
61 "A hack for RWG for univariate polys. Causes SOLVE not to get called
62 so that sqrts and cube roots will not be generated."
63 in-core)
65 (defmacro merrset (l)
66 `(let ((errset t) (unbind (cons bindlist loclist)) val)
67 (setq val (errset ,l))
68 (when (null val) (errlfun1 unbind))
69 val))
71 (defmfun $algsys (lhslist varxlist &aux varlist genvar)
72 ;; (declare (special varxlist)) ;;??
73 (setq $%rnum_list (list '(mlist)))
74 (cond ((not ($listp lhslist))
75 (merror (intl:gettext "algsys: first argument must be a list; found ~M") lhslist))
76 ((not ($listp varxlist))
77 (merror (intl:gettext "algsys: second argument must be a list; found ~M") varxlist)))
78 (let ((tlhslist nil) (*tvarxlist* nil) (solnlist nil) ($ratprint nil)
79 ;; GCL seems to read 1e-7 as zero, but only when compiling. Incantations
80 ;; based on 1d-7, 1l-7 etc. don't seem to make any difference.
81 ($ratepsilon #-gcl 1e-7
82 #+gcl (float 1/10000000))
83 ($keepfloat nil)
84 (varlist (reverse (cdr varxlist)))
85 (genvar nil) ($ratfac nil) ($breakup nil)
86 ($solvefactors nil) (*roots nil) (*failures nil)
87 (*ivar* nil) ($polyfactor nil) (varxl nil)
88 ($infeval nil) ($numer nil) ($float nil)
89 (numerflg $numer))
90 (dolist (var (cdr ($listofvars (list '(mlist simp) lhslist varxlist))))
91 (if (and (symbolp var) (not (constant var)))
92 (setq varxl (cons var varxl))))
93 (orderpointer varlist)
94 (setq tlhslist
95 (mapcar #'(lambda (q) (cadr (ratf (meqhk q))))
96 (cdr lhslist)))
97 (setq *ivar* (caadr (ratf '$%i)))
98 (setq *tvarxlist*
99 (mapcar #'(lambda (q)
100 (if (mnump q)
101 (merror (intl:gettext "algsys: variable cannot be a number; found ~M") q)
102 (caadr (ratf q))))
103 (cdr varxlist)))
104 (putorder *tvarxlist*)
105 (mbinding (varxl varxl)
106 (setq solnlist
107 (mapcar #'(lambda (q)
108 (addmlist
109 (bbsorteqns
110 (addparam (roundroots1 q) varxlist))))
111 (algsys tlhslist))))
112 (remorder *tvarxlist*)
113 (setq solnlist (addmlist solnlist))
114 (if numerflg
115 (let (($numer t) ($float t))
116 (resimplify solnlist))
117 solnlist)))
119 ;;; (CONDENSESOLNL TEMPSOLNL)
121 ;;; Condense a solution list, discarding any solution that is a special case of
122 ;;; another one. (For example, if the list contained [x=1, y=1] as a solution,
123 ;;; but also just [x=1], then the first solution would be discarded)
125 ;;; Destructively modifies TEMPSOLNL
126 (defun condensesolnl (tempsolnl)
127 (let (solnl)
128 (mapl (lambda (q)
129 (unless (subsetl (cdr q) (car q))
130 (push (car q) solnl)))
131 (stable-sort tempsolnl #'(lambda (a b) (> (length a) (length b)))));FIXME consider a total order function with #'sort
132 solnl))
134 ;;; (SUBSETL L1 S2)
136 ;;; Check whether some element of L1 is a subset of S2 (comparing elements with
137 ;;; ALIKE1). As a special case, if S2 is '(NIL) then return true.
138 (defun subsetl (l1 s2)
139 (or (equal s2 '(nil))
140 (member-if (lambda (x)
141 (subsetp x s2 :test #'alike1))
142 l1)))
144 (defun algsys (tlhslist)
145 (condensesolnl
146 (mapcan #'algsys0
147 (distrep (mapcar #'lofactors tlhslist)))))
149 (defun algsys0 (tlhslist)
150 (cond ((null tlhslist) (list nil))
151 ((equal tlhslist (list nil)) nil)
152 (t (algsys1 tlhslist))))
154 (defun algsys1 (tlhslist)
155 (destructuring-bind (resulteq . vartorid) (findleastvar tlhslist)
156 (bakalevel (algsys
157 (mapcar #'(lambda (q)
158 (if (among vartorid q)
159 (presultant q resulteq vartorid)
161 (remove resulteq tlhslist :test #'equal)))
162 tlhslist vartorid)))
164 (defun addmlist (l)
165 (cons '(mlist) l))
167 (defmacro what-the-$ev (&rest l)
168 ;; macro for calling $EV when you are not really
169 ;; sure why you are calling it, but you want the
170 ;; features of multiple evaluations and unpredictabiltiy
171 ;; anyway.
172 `(meval (list '($ev) ,@l)))
174 (defun rootsp (asolnset eqn) ;eqn is ((MLIST) eq deriv)
175 (let (rr ($keepfloat t) ($numer t) ($float t))
176 (setq rr (what-the-$ev eqn asolnset)) ; ratsimp?
177 (cond ((and (complexnump (cadr rr)) (complexnump (caddr rr)))
178 (< (cabs (cadr rr))
179 (* $algdelta (max 1 (cabs (caddr rr))))))
180 (t nil))))
182 (defun round1 (a)
183 (cond ((floatp a)
184 (setq a (maxima-rationalize a))
185 (fpcofrat1 (car a) (cdr a)))
186 (t a)))
188 (defun roundrhs (eqn)
189 (list (car eqn) (cadr eqn) (round1 (caddr eqn))))
191 (defun roundroots1 (lsoln)
192 (mapcar #'roundrhs lsoln))
194 (defun bbsorteqns (l)
195 (sort (copy-list l) #'orderlessp))
197 (defun putorder (tempvarl)
198 (do ((n 1 (1+ n))
199 (tempvarl tempvarl (cdr tempvarl)))
200 ((null tempvarl) nil)
201 (putprop (car tempvarl) n 'varorder)))
203 (defun remorder (gvarl)
204 (mapc #'(lambda (x) (remprop x 'varorder)) gvarl))
207 (defun orderlessp (eqn1 eqn2)
208 (< (get (caadr (ratf (cadr eqn1))) 'varorder)
209 (get (caadr (ratf (cadr eqn2))) 'varorder)))
211 (defun addparam (asolnsetl varxlist)
212 (cond ((= (length asolnsetl) (length *tvarxlist*))
213 asolnsetl)
215 (do ((tvarxl (cdr varxlist) (cdr tvarxl))
216 (defvar (mapcar #'cadr asolnsetl))
217 (var) (param))
218 ((null tvarxl) asolnsetl)
219 (setq var (car tvarxl))
220 (cond ((memalike var defvar) nil)
221 (t (setq param (make-param)
222 asolnsetl (cons (list '(mequal) var param)
223 (cdr (maxima-substitute
224 param var
225 (addmlist asolnsetl)))))))))))
227 (declare-top (special *vardegs*))
229 ;;; (FINDLEASTVAR LHSL)
231 ;;; Iterate over the polynomials in LHSL, trying to find a "least var", which is
232 ;;; a variable that will hopefully be easiest to solve for. Variables from
233 ;;; *TVARXLIST* and their products are considered.
235 ;;; For example, if *TVARXLIST* contains x, y and we only considered the
236 ;;; polynomial x^3 + y^2 + x then we'd have a least var of y with degree 2. If c
237 ;;; is not in *TVARXLIST* then we'd get the same answer from x^3 + c*y^2 + x
238 ;;; because such variables are just ignored. However, x^3 + x^2*y^2 would yield
239 ;;; x with degree 3 because the mixed term x^2*y^2 has higher total degree.
241 ;;; The function returns the polynomial with the variable with minimal maximum
242 ;;; degree (as described above), together with that variable.
244 ;;; Mixed terms are mostly ignored, but consider this pair of polynomials:
245 ;;; [x*y+1, x^3+1]. In the first polynomial, the only non-constant term is
246 ;;; mixed. Its degree in the first polynomial is 2 which is less than 3, so that
247 ;;; first polynomial is returned along with its leading variable.
248 (defun findleastvar (lhsl)
249 (let ((*vardegs*)
250 (leasteq) (leastvar)
251 ;; most-positive-fixnum is larger than any polynomial degree, so we can
252 ;; initialise with this and be certain to replace it on the first
253 ;; iteration.
254 (leastdeg most-positive-fixnum))
255 (declare (special *vardegs*))
256 (loop
257 for teq in lhsl
258 for *vardegs* = (getvardegs teq)
259 for tdeg = (killvardegsc teq)
260 do (loop
261 for q in *vardegs*
262 if (<= (cdr q) leastdeg)
263 do (setq leastdeg (cdr q)
264 leasteq teq
265 leastvar (car q)))
266 if (< tdeg leastdeg)
267 do (setq leastdeg tdeg
268 leasteq teq
269 leastvar (car teq)))
270 (cons leasteq leastvar)))
272 ;;; DO-POLY-TERMS
274 ;;; Iterate over the terms in a polynomial, POLY, executing BODY with LE and LC
275 ;;; bound to the exponent and coefficient respectively of each term. If RESULT
276 ;;; is non-NIL, it is evaluated to give a result when the iteration finishes.
277 (defmacro do-poly-terms ((le lc poly &optional result) &body body)
278 (let ((pt (gensym)))
279 `(do ((,pt (p-terms ,poly) (pt-red ,pt)))
280 ((null ,pt) ,result)
281 (let ((,le (pt-le ,pt))
282 (,lc (pt-lc ,pt)))
283 ,@body))))
285 ;;; (KILLVARDEGSC POLY)
287 ;;; For each monomial in POLY that is mixed in the variables in *VARDEGS*
288 ;;; (i.e. has more than one variable from *VARDEGS* with positive exponent),
289 ;;; iterate over all but the first variable, checking to see whether its degree
290 ;;; in the monomial is at least as high as that in *VARDEGS*. If so, delete that
291 ;;; variable and its degree from *VARDEGS*.
293 ;;; Returns the maximum total degree of any term in the polynomial, summing
294 ;;; degrees over the variables in *VARDEGS*.
295 (defun killvardegsc (poly)
296 (if (pconstp poly)
298 (let ((tdeg 0))
299 (do-poly-terms (le lc poly tdeg)
300 (setf tdeg (max tdeg (+ le
301 (if (= le 0)
302 (killvardegsc lc)
303 (killvardegsn lc)))))))))
305 ;;; (KILLVARDEGSN POLY)
307 ;;; For each monomial in POLY, look at its degree in each variable in
308 ;;; *TVARXLIST*. If the degree is at least as high as that recorded in
309 ;;; *VARDEGS*, delete that variable and its degree from *VARDEGS*.
311 ;;; Returns the maximum total degree of any term in the polynomial, summing
312 ;;; degrees over the variables in *VARDEGS*.
313 (defun killvardegsn (poly)
314 (declare (special *vardegs*))
315 (cond
316 ((pconstp poly) 0)
318 (let ((x (assoc (p-var poly) *vardegs* :test #'eq)))
319 (when (and x (<= (cdr x) (p-le poly)))
320 (setq *vardegs* (delete x *vardegs* :test #'equal))))
321 (let ((tdeg 0))
322 (do-poly-terms (le lc poly tdeg)
323 (setf tdeg (max tdeg (+ le (killvardegsn lc)))))))))
325 ;;; (GETVARDEGS POLY)
327 ;;; Return degrees of POLY's monomials in the variables for which we're
328 ;;; solving. Ignores mixed terms (like x*y). Results are returned as an alist
329 ;;; with elements (VAR . DEGREE).
331 ;;; For example, if *TVARXLIST* is '(x y) and we are looking at the polynomial
332 ;;; x^2 + y^2, we have
334 ;;; (GETVARDEGS '(X 2 1 0 (Y 2 1))) => ((X . 2) (Y . 2))
336 ;;; Variables that aren't in *TVARXLIST* are assumed to come after those that
337 ;;; are. For example c*x^2 would look like
339 ;;; (GETVARDEGS '(X 2 (C 1 1))) => ((X . 2))
341 ;;; Mixed powers are ignored, so x*y + y looks like:
343 ;;; (GETVARDEGS '(X 1 (Y 1 1) 0 (Y 1 1))) => ((Y . 1))
345 (defun getvardegs (poly)
346 (cond ((pconstp poly) nil)
347 ((pconstp (caddr poly))
348 (cons (cons (car poly) (cadr poly))
349 (getvardegs (ptterm (cdr poly) 0))))
350 (t (getvardegs (ptterm (cdr poly) 0)))))
352 (declare-top (unspecial *vardegs*))
354 (defun pconstp (poly)
355 (or (atom poly) (not (member (car poly) *tvarxlist* :test #'eq))))
357 ;;; (PFREEOFMAINVARSP POLY)
359 ;;; If POLY isn't a polynomial in the variables for which we're solving,
360 ;;; disrep it and simplify appropriately.
361 (defun pfreeofmainvarsp (poly)
362 (if (or (atom poly)
363 (member (car poly) *tvarxlist* :test #'eq))
364 poly
365 (simplify-after-subst (pdis poly))))
367 ;;; (LOFACTORS POLY)
369 ;;; If POLY is a polynomial in one of the variables for which we're solving,
370 ;;; then factor it into a list of factors (where the result returns factors
371 ;;; alternating with their multiplicity in the same way as PFACTOR).
373 ;;; If POLY is not a polynomial in one of the solution variables, return NIL.
374 (defun lofactors (poly)
375 (let ((main-var-poly (pfreeofmainvarsp poly)))
376 (cond
377 ((pzerop main-var-poly) '(0))
379 ;; If POLY isn't a polynomial in our chosen variables, RADCAN will return
380 ;; something whose CAR is a cons. In that case, or if the polynomial is
381 ;; something like a number, there are no factors to extract.
382 ((or (atom main-var-poly)
383 (not (atom (car main-var-poly))))
384 nil)
387 (do ((tfactors (pfactor main-var-poly) (cddr tfactors))
388 (lfactors))
389 ((null tfactors) lfactors)
390 (let ((main-var-factor (pfreeofmainvarsp (car tfactors))))
391 (cond
392 ((pzerop main-var-factor)
393 (return (list 0)))
394 ((and (not (atom main-var-factor))
395 (atom (car main-var-factor)))
396 (push (pabs main-var-factor) lfactors)))))))))
398 ;;; (COMBINEY LISTOFL)
400 ;;; Combine "independent" lists in LISTOFL. If all the lists have empty pairwise
401 ;;; intersections, this returns all selections of items, one from each
402 ;;; list. Destructively modifies LISTOFL.
404 ;;; Selections are built up starting at the last list. When building, if there
405 ;;; would be a repeated element because the list we're about to select from has
406 ;;; nonempty intersection with an existing partial selections then elements from
407 ;;; the current list aren't added to this selection.
409 ;;; COMBINEY guarantees that no list in the result has two elements that are
410 ;;; ALIKE1 each other.
412 ;;; This is used to enumerate combinations of solutions from multiple
413 ;;; equations. Each entry in LISTOFL is a list of possible solutions for an
414 ;;; equation. A solution for the set of equations is found by looking at
415 ;;; (compatible) combinations of solutions.
417 ;;; (I don't know why the non-disjoint behaviour works like this. RJS 1/2015)
418 (defun combiney (listofl)
419 (unless (member nil listofl)
420 (combiney1 (delete '(0) listofl :test #'equal))))
422 ;;; DB (2016-09-13) Commit a158b1547 introduced a regression (SF bug 3210)
423 ;;; It: - restructured combiney
424 ;;; - used ":test #'alike1" in place of "test #'equal" in combiney1
425 ;;; Reverting the change to combiney1 restores previous behaviour.
426 ;;; I don't understand algsys internals and haven't analysed this further.
427 (defun combiney1 (listofl)
428 (cond ((null listofl) (list nil))
429 (t (mapcan #'(lambda (r)
430 (if (intersection (car listofl) r :test #'equal)
431 (list r)
432 (mapcar #'(lambda (q) (cons q r)) (car listofl))))
433 (combiney1 (cdr listofl))))))
435 (defun midpnt (l)
436 (rhalf (rplus* (car l) (cadr l))))
438 (defun rflot (l)
439 (let ((rr (midpnt l)))
440 (if realonlyratnum (list '(rat) (car rr) (cdr rr))
441 (/ (+ 0.0 (car rr)) (cdr rr)))))
443 (defun memberroot (a x eps)
444 (cond ((null x) nil)
445 ((< (abs (- a (car x)))
446 (/ (+ 0.0 (car eps)) (cdr eps)))
448 (t (memberroot a (cdr x) eps))))
450 (defun commonroots (eps solnl1 solnl2)
451 (cond ((null solnl1) nil)
452 ((memberroot (car solnl1) solnl2 eps)
453 (cons (car solnl1) (commonroots eps (cdr solnl1) solnl2)))
454 (t (commonroots eps (cdr solnl1) solnl2))))
456 ;; (REMOVE-MULT L)
458 ;; Return a copy of L with all elements in odd positions removed. This is so
459 ;; named because some code returns roots and multiplicities in the format
461 ;; (ROOT0 MULT0 ROOT1 MULT1 ... ROOTN MULTN)
463 ;; Calling REMOVE-MULT on such a list removes the multiplicities.
464 (defun remove-mult (l)
465 (and l (cons (car l) (remove-mult (cddr l)))))
467 (defun punivarp (poly)
468 ;; Check if called with the number zero, return nil.
469 ;; Related bugs: SF[609466], SF[1430379], SF[1663399]
470 (when (and (numberp poly) (= poly 0)) (return-from punivarp nil))
471 (do ((l (cdr poly) (cddr l)))
472 ((null l) t)
473 (or (numberp (cadr l))
474 (and (eq (caadr l) *ivar*)
475 (punivarp (cadr l)))
476 (return nil))))
478 ;; (REALONLY ROOTSL)
480 ;; Return only the elements of ROOTSL whose $IMAGPART simplifies to zero with
481 ;; SRATSIMP. (Note that this a subset of "the real roots", because SRATSIMP may
482 ;; not be able to check that a given expression is zero)
483 (defun realonly (rootsl)
484 (remove-if-not (lambda (root)
485 (equal 0 (sratsimp ($imagpart (caddr root)))))
486 rootsl))
489 (defun presultant (p1 p2 var)
490 (cadr (ratf (simplify ($resultant (pdis p1) (pdis p2) (pdis (list var 1 1)))))))
492 (defun ptimeftrs (l)
493 (prog (ll)
494 (setq ll (cddr l))
495 (cond ((null ll) (return (car l)))
496 (t (return (ptimes (car l) (ptimeftrs ll)))))))
498 ;; (EBAKSUBST SOLNL LHSL)
500 ;; Substitute a solution for one variable back into the "left hand side
501 ;; list". If the equation had to be solved for multiple variables, this allows
502 ;; us to use the solution for a first variable to feed in to the equation for
503 ;; the next one along.
505 ;; As well as doing the obvious substitution, EBAKSUBST also simplifies with
506 ;; $RADCAN (presumably, E stands for Exponential)
507 (defun ebaksubst (solnl lhsl)
508 (mapcar #'(lambda (q) (ebaksubst1 solnl q)) lhsl))
510 (defun ebaksubst1 (solnl q)
511 (let ((e ($substitute `((mlist) ,@solnl) (pdis q))))
512 (setq e (simplify-after-subst e))
513 (cadr (ratf e))))
515 (defun baksubst (solnl lhsl)
516 (setq lhsl (delete 't (mapcar #'(lambda (q) (car (merrset (baksubst1 solnl q))))
517 lhsl)
518 :test #'eq)) ;catches arith. ovfl
519 (if (member nil lhsl :test #'eq)
520 (list nil)
521 lhsl))
523 (defun baksubst1 (solnl poly)
524 (let* (($keepfloat (not $realonly)) ;sturm1 needs poly with
525 (poly1 ;integer coefs
526 (cdr (ratf (what-the-$ev (pdis poly)
527 (cons '(mlist) solnl)
528 '$numer)))))
529 (cond ((and (complexnump (pdis (car poly1)))
530 (numberp (cdr poly1)))
531 (rootsp (cons '(mlist) solnl)
532 (list '(mlist) (pdis poly) (tayapprox poly))))
533 (t (car poly1)))))
535 (defun complexnump (p)
536 (let ((p (cadr (ratf ($ratsimp p)))))
537 (or (numberp p)
538 (eq (pdis (pget (car p))) '$%i))))
540 ;; (SIMPLIFY-AFTER-SUBST EXPR)
542 ;; Simplify EXPR after substitution of a partial solution.
544 ;; Focus is on constant expressions:
545 ;; o failure to reduce a constant expression that is equivalent
546 ;; to zero causes solutions to be falsely rejected
547 ;; o some operations, such as the reduction of nested square roots,
548 ;; requires known sign and ordering of all terms
549 ;; o inappropriate simplification by $RADCAN introduced errors
550 ;; $radcan(sqrt(-1/(1+%i))) => exhausts heap
551 ;; $radcan(sqrt(6-3^(3/2))) > 0 => sqrt(sqrt(3)-2)*sqrt(3)*%i < 0
553 ;; Problems from bug reports showed that further simplification of
554 ;; non-constant terms, with incomplete information, could lead to
555 ;; missed roots or unwanted complexity.
557 ;; $ratsimp with algebraic:true can transform
558 ;; sqrt(2)*sqrt(-1/(sqrt(3)*%i+1)) => (sqrt(3)*%i)/2+1/2
559 ;; but $rectform is required for
560 ;; sqrt(sqrt(3)*%i-1)) => (sqrt(3)*%i)/sqrt(2)+1/sqrt(2)
561 ;; and $rootscontract is required for
562 ;; sqrt(34)-sqrt(2)*sqrt(17) => 0
563 (defun simplify-after-subst (expr)
564 "Simplify expression after substitution"
565 (let (($keepfloat t) ($algebraic t) (e expr)
566 e1 e2 tmp (growth-factor 1.2)
567 (genvar nil) (varlist nil)
568 ($rootsconmode t) ($radexpand t))
569 ;; Try two approaches
570 ;; 1) ratsimp
571 ;; 2) if $constantp(e) sqrtdenest + rectform + rootscontract + ratsimp
572 ;; take smallest expression
573 (setq e1 (sratsimp e))
574 (if ($constantp e)
575 (progn
576 (setq e ($sqrtdenest e))
577 ;; Rectform does more than is wanted. A function that denests and
578 ;; rationalizes nested complex radicals would be better.
579 ;; Limit expression growth. The factor is based on trials.
580 (setq tmp ($rectform e))
581 (when (< (conssize tmp) (* growth-factor (conssize e)))
582 (setq e tmp))
583 (setq e ($rootscontract e))
584 (setq e2 (sratsimp e))
585 (if (< (conssize e1) (conssize e2)) e1 e2))
586 e1)))
588 ;; (BAKALEVEL SOLNL LHSL VAR)
590 ;;; Recursively try to find a solution to the list of polynomials in LHSL. SOLNL
591 ;;; should be a non-empty list of partial solutions (for example, these might be
592 ;;; solutions we've already found for x when we're solving for x and y).
594 ;;; BAKALEVEL works over each partial solution. This should itself be a list. If
595 ;;; it is non-nil, it is a list of equations for the variables we're trying to
596 ;;; solve for ("x = 3 + y" etc.). In this case, BAKALEVEL substitutes these
597 ;;; solutions into the system of equations and then tries to solve the
598 ;;; result. On success, it merges the partial solutions in SOLNL with those it
599 ;;; gets recursively.
601 ;;; If a partial solution is nil, we don't yet have any partial information. If
602 ;;; there is only a single polynomial to solve in LHSL, we try to solve it in
603 ;;; the given variable, VAR. Otherwise we choose a variable of lowest degree
604 ;;; (with FINDLEASTVAR), solve for that (with CALLSOLVE) and then recurse.
605 (defun bakalevel (solnl lhsl var)
606 (loop for q in solnl nconcing (bakalevel1 q lhsl var)))
608 (defun bakalevel1 (solnl lhsl var)
609 (cond
610 ((not (exactonly solnl))
611 (mergesoln solnl (apprsys (baksubst solnl lhsl))))
612 (solnl
613 (mergesoln solnl (algsys (ebaksubst solnl lhsl))))
614 ((cdr lhsl)
615 (let ((poly-and-var (findleastvar lhsl)))
616 (bakalevel (callsolve poly-and-var)
617 (remove (car poly-and-var) lhsl :test #'equal)
618 var)))
619 ;; LHSL contains one polynomial and we try to solve in one variable VAR.
620 ;; CALLSOLVE can miss solutions when the coefficient of the highest order
621 ;; term in VAR contains other variables in *TVARXLIST**.
622 ;; BAKALEVELSOLVE looks for these missed solutions.
623 (t (nconc (callsolve (cons (car lhsl) var))
624 (bakalevelsolve (car lhsl) var)))))
627 ;; (EVERY-ATOM PRED X)
629 ;; Evaluates to true if (PRED Y) is true for every atom Y in the cons tree X.
630 (defun every-atom (pred x)
631 (if (atom x)
632 (funcall pred x)
633 (and (every-atom pred (car x))
634 (every-atom pred (cdr x)))))
636 ;; (EXACTONLY SOLNL)
638 ;; True if the list of solutions doesn't contain any terms that look inexact
639 ;; (just floating point numbers, unless realonlyratnum is true)
640 (defun exactonly (solnl)
641 (every-atom (lambda (x)
642 (and (not (floatp x))
643 (or (null realonlyratnum)
644 (not (eq x 'rat)))))
645 solnl))
647 ;; (MERGESOLN ASOLN SOLNL)
649 ;; For each solution S in SOLNL, evaluate each element of ASOLN in light of S
650 ;; and, collecting up the results and prepending them to S. If evaluating an
651 ;; element in light of S caused an error, ignore the combination of ASOLN and S.
652 (defun mergesoln (asoln solnl)
653 (let ((unbind (cons bindlist loclist))
654 (errorsw t))
655 (macrolet ((catch-error-t (&body body)
656 `(let ((result (catch 'errorsw ,@body)))
657 (when (eq result t)
658 (errlfun1 unbind))
659 result)))
660 (loop
661 for q in solnl
662 for result =
663 (catch-error-t
664 (append (mapcar (lambda (r)
665 (what-the-$ev r (cons '(mlist) q)))
666 asoln)
668 if (not (eq result t)) collect result))))
670 ;; (CALLSOLVE PV)
672 ;; Try to solve a polynomial with respect to the given variable. PV is a cons
673 ;; pair (POLY . VAR). On success, return a list of solutions. Each solution is
674 ;; itself a list, whose elements are equalities (one for each variable in the
675 ;; equation). If we determine that there aren't any solutions, return '(NIL).
677 ;; If POLY is in more than one variable or if it can clearly be solved by the
678 ;; quadratic formula (BIQUADRATICP), we always call SOLVE to try to get an exact
679 ;; solution. Similarly if the user has set the $ALGEXACT variable to true.
681 ;; Otherwise, or if SOLVE fails, we try to find an approximate solution with a
682 ;; call to CALLAPPRS.
684 ;; SOLVE introduces solutions with nested radicals, which causes problems
685 ;; in EBAKSUBST1. Try to clean up the solutions now.
686 (defun callsolve (pv)
687 (mapcar #'callsolve2 (callsolve1 pv)))
689 (defun callsolve1 (pv)
690 (let ((poly (car pv))
691 (var (cdr pv))
692 (varlist varlist)
693 (genvar genvar)
694 (*roots nil)
695 (*failures nil)
696 ($programmode t))
697 (cond ((or $algexact
698 (not (punivarp poly))
699 (biquadraticp poly))
700 ;; Call SOLVE to try to solve POLY. When it returns, the solutions it
701 ;; found end up in *ROOTS. *FAILURES contains expressions that, if
702 ;; solved, would lead to further solutions.
703 (solve (pdis poly) (pdis (list var 1 1)) 1)
704 (if (null (or *roots *failures))
705 ;; We're certain there are no solutions
706 (list nil)
707 ;; Try to find approximate solutions to the terms that SOLVE gave
708 ;; up on (in *FAILURES) and remove any roots from SOLVE that
709 ;; aren't known to be real if $REALONLY is true.
710 (append (mapcan (lambda (q)
711 (callapprs (cadr (ratf (meqhk q)))))
712 (remove-mult *failures))
713 (mapcar #'list
714 (if $realonly
715 (realonly (remove-mult *roots))
716 (remove-mult *roots))))))
717 (t (callapprs poly)))))
719 (defun callsolve2 (l)
720 "Simplify solution returned by callsolve1"
721 ;; l is a single element list '((mequal simp) var expr)
722 (let ((e (first l)))
723 `(((,(mop e)) ,(second e) ,(simplify-after-subst (third e))))))
725 ;;; (BIQUADRATICP POLY)
727 ;;; Check whether POLY is biquadratic in its main variable: either of degree at
728 ;;; most two or of degree four and with only even powers.
729 (defun biquadraticp (poly)
730 (or (atom poly)
731 (if algnotexact
732 (< (p-le poly) 2)
733 (or (< (p-le poly) 3)
734 (and (= (p-le poly) 4) (biquadp1 (p-red poly)))))))
736 (defun biquadp1 (terms)
737 (or (null terms)
738 (and (or (= (pt-le terms) 2) (= (pt-le terms) 0))
739 (biquadp1 (pt-red terms)))))
741 ;;; (CALLAPPRS POLY)
743 ;;; Try to find approximate solutions to POLY, which should be a polynomial in a
744 ;;; single variable. Uses STURM1 if we're only after real roots (because
745 ;;; $REALONLY is set). Otherwise, calls $ALLROOTS.
746 (defun callapprs (poly)
747 (unless (punivarp poly)
748 (merror (intl:gettext "algsys: Couldn't reduce system to a polynomial in one variable.")))
749 (let ($dispflag)
750 (if $realonly
751 (let ((dis-var (pdis (list (car poly) 1 1))))
752 (mapcar #'(lambda (q)
753 (list (list '(mequal) dis-var (rflot q))))
754 (sturm1 poly (cons 1 $algepsilon))))
755 (mapcar #'list
756 (let* (($programmode t)
757 (roots (cdr ($allroots (pdis poly)))))
758 (if (eq (caaar roots) 'mequal)
759 roots
760 (cdr roots)))))))
762 (defun apprsys (lhsl)
763 (cond ((null lhsl) (list nil))
765 (do ((tlhsl lhsl (cdr tlhsl))) (nil)
766 (cond ((null tlhsl)
767 ;; SHOULD TRY TO BE MORE SPECIFIC: "TOO COMPLICATED" IN WHAT SENSE??
768 (merror (intl:gettext "algsys: system too complicated; give up.")))
769 ((pconstp (car tlhsl)) (return nil))
770 ((punivarp (car tlhsl))
771 (return (bakalevel (callapprs (car tlhsl))
772 lhsl nil))))))))
774 (defun tayapprox (p)
775 (cons '(mplus)
776 (mapcar #'(lambda (x)
777 (list '(mycabs) (pdis (ptimes (list x 1 1)
778 (pderivative p x)))))
779 (listovars p))))
781 (defun mycabs (x)
782 (and (complexnump x) (cabs x)))
784 ;;; (DISTREP LOL)
786 ;;; Take selections from LOL, a list of lists, using COMBINEY. When used by
787 ;;; ALGSYS, the elements of the lists are per-equation solutions for some system
788 ;;; of equations. COMBINEY combines the per-equation solutions into prospective
789 ;;; solutions for the entire system.
791 ;;; These prospective solutions are then filtered with CONDENSESOLNL, which
792 ;;; discards special cases of more general solutions.
794 ;;; (I don't understand why this reversal has to be here, but we get properly
795 ;;; wrong solutions to some of the testsuite functions without it. Come back to
796 ;;; this... RJS 1/2015)
797 (defun distrep (lol)
798 (condensesolnl (mapcar #'reverse (combiney lol))))
800 (defun exclude (l1 l2)
801 (cond ((null l2)
802 nil)
803 ((member (car l2) l1 :test #'equal)
804 (exclude l1 (cdr l2)))
806 (cons (car l2) (exclude l1 (cdr l2))))))
808 ;;; (BAKALEVELSOLVE P VAR)
810 ;;; P is a polynomial in VAR. VAR may not be the main variable.
811 ;;; We are trying to solve P in terms of the single variable VAR, so
812 ;;; the other solution variables (in *TVARXLIST*) are treated as constants.
814 ;;; CALLSOLVE can miss solutions when the leading (highest order)
815 ;;; coefficient C of VAR contains other variables in *TVARXLIST*.
816 ;;; Apparently C is implicitly assumed to be non-zero.
818 ;;; Seek these missing solutions by:
819 ;;; - finding N, the highest power of VAR in P
820 ;;; - separating P into C*VAR^N + D (VAR may not be the main variable in P)
821 ;;; - look for solutions of form (C=0,D=0)
823 ;;; An example is solving a*b-c*d in terms of [a,b,c,d]
825 (defun bakalevelsolve (p var)
826 (let (n c d)
827 (cond
828 ;; a bare coefficient isn't an equation
829 ((pcoefp p) nil)
830 ;; N is highest power of VAR in polynomial P.
831 ;; No equation in VAR if N=0. No solution.
832 ((= (setq n (p-hipow-var p var)) 0) nil)
834 ;; express P as C*VAR^N + D
835 (setf (values c d) (p-coef-x p var n))
836 (if (p-allvars c) ; Does C contain any variables from *TVARXLIST*
837 (algsys `(,c ,d)) ; Try and solve C=0 and D=0 using algsys
838 nil))))) ; C is freeof of *TVARXLIST*. No solution.
840 ;;; De-duplicated list of variables in polynomial P
841 (defun p-allvars (p)
842 (unless (pcoefp p) (remove-duplicates (p-allvars1 p))))
844 ;;; List of variables in polynomial P. May contain duplicates.
845 (defun p-allvars1 (p)
846 (unless (pcoefp p)
847 (cons
848 (p-var p) ; the main variable of poly
849 (loop ; Recusively extract variables from coefficients.
850 for (nil ci) on (p-terms p) by #'cddr
851 if (not (pcoefp ci)) append (p-allvars1 ci)))))
853 ;;; Maximum degree of variable V in polynomial P
854 ;;; V may not be the main variable in P
855 (defun p-hipow-var (p v)
856 (cond
857 ((pcoefp p) 0) ; bare coefficient has degree 0
858 ((eq (p-var p) v) (p-le p)) ; V is main variable - return leading exponent
860 (loop ; Recusively search through coefficients of p
861 for (nil c) on (p-terms p) by #'cddr
862 maximize (p-hipow-var c v)))))
864 ;;; (P-COEF-X P X N)
866 ;;; Separate multivariable polynomial P with main variable V into C*x^n + D
867 ;;; where X may be different to V. Return (values C D)
868 ;;; Assumes terms of P are in decending order
869 (defun p-coef-x (p x n)
870 (cond
871 ((pcoefp p) ; p is a bare coefficient
872 (if (= n 0)
873 (values p (pzero)) ; c = bare coef, d = 0
874 (values (pzero) p))) ; c = 0, d = bare coef
875 ((eq (p-var p) x) ; main variable V in P is X
876 (p-coef-main p n))
878 ;; P is polynomial with main variable V other than X
879 ;; iterate over coefficients ai
880 ;; find (ci di) such that ai = ci*x^n + di
881 ;; C = ck*v^k + ... + c0*v^0, a polynomial in v
882 ;; D = dk*v^k + ... + d0*v^0, a polynomial in v
883 (loop
884 with terms = (p-terms p) with v = (p-var p) with ci with di
885 for (i ai) on terms by #'cddr
886 do (setf (values ci di) (p-coef-x ai x n))
887 unless (pzerop ci) append `(,i ,ci) into cterms
888 unless (pzerop di) append `(,i ,di) into dterms
889 finally (return (values (psimp v cterms) (psimp v dterms)))))))
892 ;;; (P-COEF-MAIN P N)
894 ;;; Separate multivariable polynomial P with main variable X into C*x^n + D
895 ;;; Return (values C D)
896 ;;; Assumes terms of P are in decending order
897 (defun p-coef-main (p n)
898 (if (pcoefp p) ; bare coefficient
899 (if (= n 0)
900 (values p 0) ; c = bare coef & d = 0
901 (values 0 p)) ; c = 0 & d = bare coef
902 (loop ; proper polynomial
903 with L = (p-terms p) ; list of terms in polynomial
904 with var = (p-var p) ; main variable
905 for i = (pop L) ; power of term
906 for ai = (pop L) ; coefficient of term x^i
907 while (>= i n) ; exit via finally if n-th power not present
908 if (> i n)
909 append `(,i ,ai) into terms ; accumulate higher order terms
910 else ; have i==n so C=ai. Construct D and return
911 do (return (values ai (psimp var (append terms L))))
912 while L ; exit via finally if all coefficients examined
913 finally (return (values 0 p)))))