Rename specvar integer-info to *integer-info*
[maxima.git] / src / limit.lisp
blobc4e9bb1b8488a82058f6cf652f25a0de006b9adf
1 ;;; -*- Mode: Lisp; Package: Maxima; Syntax: Common-Lisp; Base: 10 -*- ;;;;
2 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3 ;;; The data in this file contains enhancements. ;;;;;
4 ;;; ;;;;;
5 ;;; Copyright (c) 1984,1987 by William Schelter,University of Texas ;;;;;
6 ;;; All rights reserved ;;;;;
7 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
8 ;;; (c) Copyright 1982 Massachusetts Institute of Technology ;;;
9 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
11 (in-package :maxima)
13 (macsyma-module limit)
16 ;;; **************************************************************
17 ;;; ** **
18 ;;; ** LIMIT PACKAGE **
19 ;;; ** **
20 ;;; **************************************************************
22 ;;; I believe a large portion of this file is described in Paul
23 ;;; Wang's thesis, "Evaluation of Definite Integrals by Symbolic
24 ;;; Manipulation," MIT/LCS/TR-92, Oct. 1971. This can be found at
25 ;;; https://web.archive.org/web/20191019131847/https://apps.dtic.mil/dtic/tr/fulltext/u2/732005.pdf
28 ;;; TOP LEVEL FUNCTION(S): $LIMIT $LDEFINT
30 (declare-top (special origval
31 *indicator numer denom exp var val
32 taylored logcombed
33 $exponentialize lhp? lhcount
34 loginprod? a context limit-assumptions
35 limit-top #+nil old-integer-info))
37 (defconstant +behavior-count+ 4)
38 (defvar *behavior-count-now*)
39 (defvar *getsignl-asksign-ok* nil)
40 (defvar *old-integer-info* nil)
42 (load-macsyma-macros rzmac)
44 (defmvar simplimplus-problems ()
45 "A list of all problems in the stack of recursive calls to simplimplus.")
47 (defmvar limit-answers ()
48 "An association list for storing limit answers.")
50 (defmvar limit-using-taylor ()
51 "Is the current limit computation using taylor expansion?")
53 (defmvar preserve-direction () "Makes `limit' return Direction info.")
55 #+nil
56 (unless (boundp 'integer-info) (setq integer-info ()))
58 ;; For limits toward infinity for the gruntz code, we assume that the limit
59 ;; variable exceeds *large-positive-number*. This value matches the value
60 ;; that the limit code uses for the same purpose.
61 (defmvar *large-positive-number* (expt 10 8))
63 ;; Don't ask sign questions about $ind.
64 (putprop '$ind t 'internal)
66 ;; This should be made to give more information about the error.
67 ;;(DEFun DISCONT ()
68 ;; (cond (errorsw (throw 'errorsw t))
69 ;; (t (merror "Discontinuity Encountered"))))
71 ;;(DEFUN PUTLIMVAL (E V)
72 ;; (let ((exp (cons '(%limit) (list e var val))))
73 ;; (cond ((not (assolike exp limit-answers))
74 ;; (setq limit-answers (cons (cons exp v) limit-answers))
75 ;; v)
76 ;; (t ()))))
78 (defun putlimval (e v &aux exp)
79 (setq exp `((%limit) ,e ,var ,val))
80 (unless (assolike exp limit-answers)
81 (push (cons exp v) limit-answers))
84 (defun getlimval (e)
85 (let ((exp (cons '(%limit) (list e var val))))
86 (assolike exp limit-answers)))
88 (defmacro limit-catch (exp var val)
89 `(let ((errorsw t))
90 (let ((ans (catch 'errorsw
91 (catch 'limit (limit ,exp ,var ,val 'think)))))
92 (if (or (null ans) (eq ans t))
94 ans))))
96 (defmfun $limit (&rest args)
97 (let ((first-try (apply #'toplevel-$limit args)))
98 (if (and (consp first-try) (eq (caar first-try) '%limit))
99 (let ((*getsignl-asksign-ok* t))
100 (apply #'toplevel-$limit args))
102 ;; The function toplevel-$limit sets $numer, $%enumer, %emode, and
103 ;; $%e_to_numlog to false. When any of these option variables are true,
104 ;; we resimplify the limit in the current context.
105 (progn
106 (when (or $numer $%enumer $%emode $%e_to_numlog)
107 (setq first-try (resimplify first-try)))
108 first-try))))
110 ;; Return true iff the expression e has a subexpression that
111 ;; is an indefinite integral.
112 (defun indefinite-integral-p (e x)
113 (cond (($mapatom e) nil)
114 ((and (eq (caar e) '%integrate) (alike x (third e)))
115 (null (fourth e)))
117 (some #'(lambda (q) (indefinite-integral-p q x)) (cdr e)))))
119 (defun toplevel-$limit (&rest args)
120 (let ((limit-assumptions ())
121 (*old-integer-info* ())
122 ($keepfloat t)
123 ($numer nil)
124 ($%enumer nil)
125 ($%emode t)
126 ($%e_to_numlog nil)
127 (limit-top t))
128 (declare (special limit-assumptions #+nil old-integer-info
129 limit-top))
130 (unless limitp
131 (setq *old-integer-info* *integer-info*)
132 (setq *integer-info* ()))
134 (unwind-protect
135 (let ((exp1 ()) (lhcount $lhospitallim) (*behavior-count-now* 0)
136 (exp ()) (var ()) (val ()) (dr ())
137 (*indicator ()) (taylored ()) (origval ())
138 (logcombed ()) (lhp? ())
139 (varlist ()) (ans ()) (genvar ()) (loginprod? ())
140 (limit-answers ()) (limitp t) (simplimplus-problems ())
141 (lenargs (length args))
142 (genfoo ()))
143 (declare (special lhcount *behavior-count-now* exp var val *indicator
144 taylored origval logcombed lhp?
145 varlist genvar loginprod? limitp))
146 (prog ()
147 (unless (or (= lenargs 3) (= lenargs 4) (= lenargs 1))
148 (wna-err '$limit))
149 ;; Is it a LIST of Things?
150 (when (setq ans (apply #'limit-list args))
151 (return ans))
152 (setq exp1 (specrepcheck (first args)))
153 (when (and (atom exp1)
154 (member exp1 '(nil t)))
155 ;; The expression is 'T or 'NIL. Return immediately.
156 (return exp1))
157 (cond ((= lenargs 1)
158 (setq var (setq genfoo (gensym)) ; Use a gensym. Not foo.
159 val 0))
161 (setq var (second args))
162 (when ($constantp var)
163 (merror (intl:gettext "limit: second argument must be a variable, not a constant; found: ~M") var))
164 (unless (or ($subvarp var) (atom var))
165 (merror (intl:gettext "limit: variable must be a symbol or subscripted symbol; found: ~M") var))
166 (setq val (infsimp (third args)))
167 ;; infsimp converts -inf to minf. it also converts -infinity to
168 ;; infinity, although perhaps this should generate the error below.
169 (when (and (not (atom val))
170 (some #'(lambda (x) (not (freeof x val)))
171 *infinities*))
172 (merror (intl:gettext "limit: third argument must be a finite value or one of: inf, minf, infinity; found: ~M") val))
173 (when (eq val '$zeroa) (setq dr '$plus))
174 (when (eq val '$zerob) (setq dr '$minus))))
175 (cond ((= lenargs 4)
176 (unless (member (fourth args) '($plus $minus) :test #'eq)
177 (merror (intl:gettext "limit: direction must be either 'plus' or 'minus'; found: ~M") (fourth args)))
178 (setq dr (fourth args))))
179 (if (and (atom var) (not (among var val)))
180 (setq exp exp1)
181 (let ((realvar var)) ;; Var is funny so make it a gensym.
182 (setq var (gensym))
183 (setq exp (maxima-substitute var realvar exp1))
184 (putprop var realvar 'limitsub)))
186 ;; When exp involves an indefinite integral whose integration variable
187 ;; is the limit variable, return a limit nounform. Do this even when
188 ;; limsubst is true. Thus limit(int(f(x),x,a) is trapped here, but
189 ;; limit(int(f(x,z),x,a) is not.
190 (when (indefinite-integral-p exp var)
191 (return (cons (list '%limit) args)))
193 ;; This returns a limit nounform for expressions such as
194 ;; limit(x < 8,x,0), limit(diff(f(x),x,x,0), and ...
195 (unless (eq var genfoo)
196 (when (limunknown exp)
197 (return `((%limit) ,@(cons exp1 (cdr args))))))
199 (setq varlist (ncons var) genvar nil origval val)
200 ;; Transform limits to minf to limits to inf by
201 ;; replacing var with -var everywhere.
202 (when (eq val '$minf)
203 (setq val '$inf
204 origval '$inf
205 exp (subin (m* -1 var) exp)))
207 ;; Transform the limit value.
208 (unless (infinityp val)
209 (unless (zerop2 val)
210 (let ((*atp* t) (realvar var))
211 ;; *atp* prevents substitution from applying to vars
212 ;; bound by %sum, %product, %integrate, %limit
213 (setq var (gensym))
214 (putprop var t 'internal)
215 (setq exp (derivative-subst exp val var realvar))
216 (setq exp (maxima-substitute (m+ val var) realvar exp))))
217 (setq val (cond ((eq dr '$plus) '$zeroa)
218 ((eq dr '$minus) '$zerob)
219 (t 0)))
220 (setq origval 0))
222 ;; Make assumptions about limit var being very small or very large.
223 ;; Assumptions are forgotten upon exit.
224 (unless (= lenargs 1)
225 (limit-context var val dr))
226 ;; Resimplify in light of new assumptions. Changing ($expand exp 1 0)
227 ;; to ($expand exp 0 0) results in a bad testsuite failure for
228 ;; (assume(a>2), limit(integrate(t/log(t),t,2,a)/a,a,inf)) and
229 ;; some testsuite results that are more messy.
230 (setq exp (resimplify
231 ($minfactorial
232 (extra-simp
233 ($expand exp 1 0)))))
235 (if (not (or (real-epsilonp val) ;; if direction of limit not specified
236 (infinityp val)))
237 (setq ans (both-side exp var val)) ;; compute from both sides
238 (progn
239 (setq exp (mabs-subst exp var val))
240 (setq ans (limit-catch exp var val));; and find limit from one side
242 ;; try gruntz
243 (if (not ans)
244 (setq ans (catch 'taylor-catch
245 (let ((silent-taylor-flag t))
246 (declare (special silent-taylor-flag))
247 (gruntz1 exp var val)))))
249 ;; try taylor series expansion if simple limit didn't work
250 (if (and (null ans) ;; if no limit found and
251 $tlimswitch ;; user says ok to use taylor and
252 (not limit-using-taylor));; not already doing taylor
253 (let ((limit-using-taylor t))
254 (declare (special limit-using-taylor))
255 (setq ans (limit-catch exp var val))))))
257 (if ans
258 (return (clean-limit-exp ans))
259 (return (cons '(%limit) args))))) ;; failure: return nounform
260 (restore-assumptions))))
262 (defun clean-limit-exp (exp)
263 (setq exp (restorelim exp))
264 (if preserve-direction exp (ridofab exp)))
266 ;; Users who want limit to map over equality (mequal) will need to do that
267 ;; manually.
268 (defun limit-list (exp1 &rest rest)
269 (if (and (mbagp exp1) (not (mequalp exp1)))
270 `(,(car exp1) ,@(mapcar #'(lambda (x) (apply #'toplevel-$limit `(,x ,@rest))) (cdr exp1)))
271 ()))
273 (defun limit-context (var val direction) ;Only works on entry!
274 (cond (limit-top
275 (assume '((mgreaterp) lim-epsilon 0))
276 (assume '((mgreaterp) prin-inf 100000000))
277 (setq limit-assumptions (make-limit-assumptions var val direction))
278 (setq limit-top ()))
279 (t ()))
280 limit-assumptions)
282 (defun make-limit-assumptions (var val direction)
283 (let ((new-assumptions))
284 (cond ((or (null var) (null val))
286 ((and (not (infinityp val)) (null direction))
288 ((eq val '$inf)
289 `(,(assume `((mgreaterp) ,var 100000000)) ,@new-assumptions))
290 ((eq val '$minf)
291 `(,(assume `((mgreaterp) -100000000 ,var)) ,@new-assumptions))
292 ((eq direction '$plus)
293 `(,(assume `((mgreaterp) ,var 0)) ,@new-assumptions)) ;All limits around 0
294 ((eq direction '$minus)
295 `(,(assume `((mgreaterp) 0 ,var)) ,@new-assumptions))
297 ()))))
299 (defun restore-assumptions ()
300 ;;;Hackery until assume and forget take reliable args. Nov. 9 1979.
301 ;;;JIM.
302 (do ((assumption-list limit-assumptions (cdr assumption-list)))
303 ((null assumption-list) t)
304 (forget (car assumption-list)))
305 (forget '((mgreaterp) lim-epsilon 0))
306 (forget '((mgreaterp) prin-inf 100000000))
307 (cond ((and (not (null *integer-info*))
308 (not limitp))
309 (do ((list *integer-info* (cdr list)))
310 ((null list) t)
311 (i-$remove `(,(cadar list) ,(caddar list))))
312 (setq *integer-info* *old-integer-info*))))
314 ;; The optional arg allows the caller to decide on the value of
315 ;; preserve-direction. Default is nil, since we immediately ridofab.
316 (defun both-side (exp var val &optional (preserve nil))
317 (let* ((preserve-direction preserve)
318 (la (toplevel-$limit exp var val '$plus)) lb)
319 ; Immediately propagate an und without trying the
320 ; other direction
321 (when (eq la '$und) (return-from both-side '$und))
322 (setf lb (toplevel-$limit exp var val '$minus))
323 ; Immediately propagate an und
324 (when (eq lb '$und) (return-from both-side '$und))
325 (let ((ra (ridofab la))
326 (rb (ridofab lb)))
327 (cond ((eq t (meqp ra rb))
329 ((and (eq ra '$ind)
330 (eq rb '$ind))
331 ; Maxima does not consider equal(ind,ind) to be true, but
332 ; if both one-sided limits are ind then we want to call
333 ; the two-sided limit ind (e.g., limit(sin(1/x),x,0)).
334 '$ind)
335 ((or (not (free la '%limit))
336 (not (free lb '%limit)))
339 (let ((infa (infinityp la))
340 (infb (infinityp lb)))
341 (cond ((and infa infb)
342 ; inf + minf => infinity
343 '$infinity)
344 ((or infa infb)
345 '$und)
347 '$ind))))))))
349 ;; Return true when Maxima should return a limit nounform for limit(e,x,var,val).
350 (defun limunknown (e)
351 (not (limit-ok e var)))
353 ;; Return true when Maxima's limit code should be able to determine limit
354 (defun limit-ok (e x)
355 (cond
356 ((mapatom e) t) ;mapatoms are OK
357 ;; return nil for an indefinite integral
358 ((and (eq (caar e) '%integrate) (alike x (third e)) (null (fourth e))) nil)
359 ;; Return true for integrate(X,z,a,b) provided (a) freeof(x,X) (b) limit-ok(a,x)
360 ;; and (c) limit-ok(b,x). The function simplim%integrate doesn't recoginize
361 ;; $limsubst, but this function does.
362 ((eq (caar e) '%integrate)
363 (and (limit-ok (fourth e) x) (limit-ok (fifth e) x))
364 (or $limsubst ($freeof (third e) x)))
365 ;; when the operator of e either (a) has a simplim%function, (b)
366 ;; is a simplifying operator (including subscripted operators),
367 ;; or (c) is $fib, check that each argument of e is OK.
369 (let* ((op (caar e))
370 (ok (or (get op 'operators)
371 (get op 'simplim%function)
372 (and (eq op 'mqapply) (get (subfunname e) 'specsimp))
373 (eq op '$fib))))
374 (and (or ok $limsubst)
375 (or (every #'(lambda(q) (limit-ok q x)) (cdr e)) ($freeof x e)))))))
377 ;; The functionality of this code has been blended into extra-simp. But
378 ;; there are some differences: (a) when e depends on the global var, this
379 ;; code converts *every* gamma function into a factorial, but extra-simp only
380 ;; converts subexpressions of the form gamma(X), where X depends on var to
381 ;; factorial form (b) this code dispatches minfactorial, but extra-simp
382 ;; doesn't.
384 ;; The function factosimp is not called by the limit code or by any
385 ;; code in source.
386 (defun factosimp(e)
387 (if (involve e '(%gamma)) (setq e ($makefact e)))
388 (cond ((involve e '(mfactorial))
389 (setq e (simplify ($minfactorial e))))
390 (t e)))
392 ;; Define sgn = csign(limit(z,var,val)). Return -1, 0, 1, or nil when
393 ;; sgn is neg, zero, pos, or complex, imaginary or unknown (including when
394 ;; the limit is ind), respectively. Also, when the limit is either zerob or zeroa,
395 ;; return 0.
397 ;; This function obeys the flag *getsignl-asksign-ok*, so it only does
398 ;; an asksign when *getsignl-asksign-ok* is true.
400 ;; When the limit is either zerob or zeroa, it's reasonable to return -1 or 1,
401 ;; respectively, but that causes a testsuite regression. Also when z is
402 ;; positive but limit(z,var,val) is ind, possibly this function could return 1, but
403 ;; it doesn't.
404 (defun getsignl (z)
405 (let ((sgn))
406 (setq z (let ((preserve-direction nil)) (limit-catch z var val)))
407 (cond
408 ;; Don't call csign on ind, und, infinity, zeroa, or zerob.
409 ;; When z is either zeroa or zerob, return 0.
410 ((or (eq z '$ind) (eq z '$und) (eq z '$infinity)) nil)
411 ((eq z '$zeroa) 0)
412 ((eq z '$zerob) 0)
414 (setq sgn (if *getsignl-asksign-ok* ($asksign z) ($csign z)))
415 (cond ((eq sgn '$pos) 1)
416 ((eq sgn '$neg) -1)
417 ((eq sgn '$zero) 0)
418 (t nil))))))
420 (defun restorelim (exp)
421 (cond ((null exp) nil)
422 ((atom exp) (or (and (symbolp exp) (get exp 'limitsub)) exp))
423 ((and (consp (car exp)) (eq (caar exp) 'mrat))
424 (cons (car exp)
425 (cons (restorelim (cadr exp))
426 (restorelim (cddr exp)))))
427 (t (cons (car exp) (mapcar #'restorelim (cdr exp))))))
429 ;; For each subexpression of e of the form abs(X), decide if abs(X) can be
430 ;; replaced by -X or by X. Define ans = limit(X,var, val) and
431 ;; bee = behavior(X,var,val). Cases:
433 ;; (a) negative (ans = -1) & decreasing (bee = -1), do abs(X) --> -X
434 ;; (b) positive (ans = 1) & increasing (bee = 1), do abs(X) --> X
435 ;; (c) zero (ans = 0) & decreasing (bee = -1), do abs(X) --> -X
436 ;; (d) zero (ans = 0) & X increasing (bee = 1), do abs(X) --> X
438 ;; This function misses cases such as abs(1-x^2) for x near 0.
439 ;; For that case, we get ans = 1 & bee = -1.
441 ;; If one-sided limits assumed both lower and upper bounds for the limit
442 ;; variable (something like 0 < x < tiny for a limit of x toward 0 from above),
443 ;; some subexpressions of the form abs(X) could be simplifed away before
444 ;; going through this function.
446 ;; This function was rewritten and algorithmally altered by Barton Willis in
447 ;; January 2024. Previously, it was responsible for the bug
448 ;; limit(abs(sin(x))/sin(x), x, inf) = 1. Also, the old version also prevented
449 ;; limit(cos(a*x),x,inf) from doing an asksign on a, and it gave an
450 ;; internal error for limit((abs(sin(x)*cos(x)-x^4) -x)/x^3,x,0,plus).
451 (defun mabs-subst (e var val)
452 (let ((ans) (bee))
453 (cond (($mapatom e) e)
454 ;; Found a subexpression of the form abs(X). Decide if its OK
455 ;; to replace abs(X) by -X or by X. We could skip this when
456 ;; X is freeof var, but I'm not sure that we win by doing do
457 ((and (consp e) (eq (caar e) 'mabs))
458 (setq e (mabs-subst (cadr e) var val)) ;recurse on mabs-subst
459 (setq ans (getsignl e))
460 (setq bee (if ans (behavior e var val) nil))
461 (cond
462 ((and (eql ans -1) (eql bee -1)) (mul -1 e)) ;negative & decreasing
463 ((and (eql ans 1) (eql bee 1)) e) ; positive & increasing
464 ((and (eql ans 0) (eql bee -1)) (mul -1 e)) ;zero & decreasing
465 ((and (eql ans 0) (eql bee 1)) e) ;zero & increasing
466 (t (ftake 'mabs e)))) ; don't know
467 ;; Map mabs-subst over a subscripted function.
468 (($subvarp (mop e))
469 (subfunmake
470 (subfunname e)
471 (mapcar #'(lambda (q) (mabs-subst q var val)) (subfunsubs e))
472 (mapcar #'(lambda (q) (mabs-subst q var val)) (subfunargs e))))
473 ;; Map mabs-subst over the expression.
474 (t (fapply (caar e)
475 (mapcar #'(lambda (q) (mabs-subst q var val)) (cdr e)))))))
477 ;; Called on an expression that might contain $INF, $MINF, $ZEROA, $ZEROB. Tries
478 ;; to simplify it to sort out things like inf^inf or inf+1.
479 (defun simpinf (exp)
480 (simpinf-ic exp (count-general-inf exp)))
482 (defun count-general-inf (expr)
483 (count-atoms-matching
484 (lambda (x) (or (infinityp x) (real-epsilonp x))) expr))
486 (defun count-atoms-matching (predicate expr)
487 "Count the number of atoms in the Maxima expression EXPR matching PREDICATE,
488 ignoring dummy variables and array indices."
489 (cond
490 ((atom expr) (if (funcall predicate expr) 1 0))
491 ;; Don't count atoms that occur as a limit of %integrate, %sum, %product,
492 ;; %limit etc.
493 ((member (caar expr) dummy-variable-operators)
494 (count-atoms-matching predicate (cadr expr)))
495 ;; Ignore array indices
496 ((member 'array (car expr)) 0)
497 (t (loop
498 for arg in (cdr expr)
499 summing (count-atoms-matching predicate arg)))))
501 (defun simpinf-ic (exp &optional infinity-count)
502 (case infinity-count
503 ;; A very slow identity transformation...
504 (0 exp)
506 ;; If there's only one infinity, we replace it by a variable and take the
507 ;; limit as that variable goes to infinity. Use $gensym in case we can't
508 ;; compute the answer and the limit leaks out.
509 (1 (let* ((val (or (inf-typep exp) (epsilon-typep exp)))
510 (var ($gensym))
511 (expr (subst var val exp))
512 (limit (toplevel-$limit expr var val)))
513 (cond
514 ;; Now we look to see whether the computed limit is any simpler than
515 ;; what we shoved in (which we'll define as "doesn't contain EXPR as a
516 ;; subtree"). If so, return it.
517 ((not (subtree-p expr limit :test #'equal))
518 limit)
520 ;; Otherwise, return the original form: apparently, we can't compute
521 ;; the limit we needed, and it's uglier than what we started with.
522 (t exp))))
524 ;; If more than one infinity, we have to be a bit more careful.
525 (otherwise
526 (let* ((arguments (mapcar 'simpinf (cdr exp)))
527 (new-expression (cons (list (caar exp)) arguments))
528 infinities-left)
529 (cond
530 ;; If any of the arguments are undefined, we are too.
531 ((among '$und arguments) '$und)
532 ;; If we ended up with something indeterminate, we punt and just return
533 ;; the input.
534 ((amongl '(%limit $ind) arguments) exp)
536 ;; Exponentiation & multiplication
537 ((mexptp exp) (simpinf-expt (first arguments) (second arguments)))
538 ((mtimesp exp) (simpinf-times arguments))
540 ;; Down to at most one infinity? We do this after exponentiation to
541 ;; avoid zeroa^zeroa => 0^0, which will raise an error rather than just
542 ;; returning und. We do it after multiplication to avoid zeroa * inf =>
543 ;; 0 * inf => 0.
544 ((<= (setf infinities-left (count-general-inf new-expression)) 1)
545 (simpinf-ic new-expression infinities-left))
547 ;; Addition
548 ((mplusp exp) (simpinf-plus arguments))
550 ;; Give up!
551 (t new-expression))))))
553 (defun simpinf-times (arguments)
554 (declare (special exp var val))
555 ;; When we have a product, we need to spot that zeroa * zerob = zerob, zeroa *
556 ;; inf = und etc. Note that (SIMPINF '$ZEROA) => 0, so a nonzero atom is not
557 ;; an infinitesimal. Moreover, we can assume that each of ARGUMENTS is either
558 ;; a number, computed successfully by the recursive SIMPINF call, or maybe a
559 ;; %LIMIT noun-form (in which case, we aren't going to be able to tell the
560 ;; answer).
561 (cond
562 ((member 0 arguments)
563 (cond
564 ((find-if #'infinityp arguments) '$und)
565 ((every #'atom arguments) 0)
566 (t exp)))
568 ((member '$infinity arguments)
569 (if (every #'atom arguments)
570 '$infinity
571 exp))
573 (t (simplimit (cons '(mtimes) arguments) var val))))
575 (defun simpinf-expt (base exponent)
576 ;; In the comments below, zero* represents one of 0, zeroa, zerob.
578 ;; TODO: In some cases we give up too early. E.g. inf^(2 + 1/inf) => inf^2
579 ;; (which should simplify to inf)
580 (case base
581 ;; inf^inf = inf
582 ;; inf^minf = 0
583 ;; inf^zero* = und
584 ;; inf^foo = inf^foo
585 ($inf
586 (case exponent
587 ($inf '$inf)
588 ($minf 0)
589 ((0 $zeroa $zerob) '$und)
590 (t (list '(mexpt) base exponent))))
591 ;; minf^inf = infinity <== Or should it be und?
592 ;; minf^minf = 0
593 ;; minf^zero* = und
594 ;; minf^foo = minf^foo
595 ($minf
596 (case exponent
597 ($inf '$infinity)
598 ($minf 0)
599 ((0 $zeroa $zerob) '$und)
600 (t (list '(mexpt) base exponent))))
601 ;; zero*^inf = 0
602 ;; zero*^minf = und
603 ;; zero*^zero* = und
604 ;; zero*^foo = zero*^foo
605 ((0 $zeroa $zerob)
606 (case exponent
607 ($inf 0)
608 ($minf '$und)
609 ((0 $zeroa $zerob) '$und)
610 (t (list '(mexpt) base exponent))))
611 ;; a^b where a is pretty much anything except for a naked
612 ;; inf,minf,zeroa,zerob or 0.
614 (cond
615 ;; When a isn't crazy, try a^b = e^(b log(a))
616 ((not (amongl (append *infinitesimals* *infinities*) base))
617 (simpinf (m^ '$%e (m* exponent `((%log) ,base)))))
619 ;; No idea. Just return what we've found so far.
620 (t (list '(mexpt) base exponent))))))
622 (defun simpinf-plus (arguments)
623 ;; We know that none of the arguments are infinitesimals, since SIMPINF never
624 ;; returns one of them. As such, we partition our arguments into infinities
625 ;; and everything else. The latter won't have any "hidden" infinities like
626 ;; lim(x,x,inf), since SIMPINF gave up on anything containing a %lim already.
627 (let ((bigs) (others))
628 (dolist (arg arguments)
629 (cond ((infinityp arg) (push arg bigs))
630 (t (push arg others))))
631 (cond
632 ;; inf + minf or the like
633 ((cdr (setf bigs (delete-duplicates bigs))) '$und)
634 ;; inf + smaller + stuff
635 (bigs (car bigs))
636 ;; I don't think this can happen, since SIMPINF goes back to the start if
637 ;; there are fewer than two infinities in the arguments, but let's be
638 ;; careful.
639 (t (cons '(mplus) others)))))
641 ;; Simplify expression with zeroa or zerob.
642 (defun simpab (small)
643 (cond ((null small) ())
644 ((member small '($zeroa $zerob $inf $minf $infinity) :test #'eq) small)
645 ((not (free small '$ind)) '$ind) ;Not exactly right but not
646 ((not (free small '$und)) '$und) ;causing trouble now.
647 ((mapatom small) small)
648 (t (let ((preserve-direction t)
649 (new-small (subst (m^ '$inf -1) '$zeroa
650 (subst (m^ '$minf -1) '$zerob small))))
651 (simpinf new-small)))))
654 ;;;*I* INDICATES: T => USE LIMIT1,THINK, NIL => USE SIMPLIMIT.
655 (defun limit (exp var val *i*)
656 (cond
657 ((among '$und exp) '$und)
658 ((eq var exp) val)
659 ((atom exp) exp)
660 ((not (among var exp))
661 (cond ((amongl '($inf $minf $infinity $ind) exp)
662 (simpinf exp))
663 ((amongl '($zeroa $zerob) exp)
664 ;; Simplify expression with zeroa or zerob.
665 (simpab exp))
666 (t exp)))
667 ((getlimval exp))
668 (t (putlimval exp (cond ((and limit-using-taylor
669 (null taylored)
670 (tlimp exp))
671 (taylim exp var val *i*))
672 ((ratp exp var) (ratlim exp))
673 ((or (eq *i* t) (radicalp exp var))
674 (limit1 exp var val))
675 ((eq *i* 'think)
676 (cond ((or (mtimesp exp) (mexptp exp))
677 (limit1 exp var val))
678 (t (simplimit exp var val))))
679 (t (simplimit exp var val)))))))
681 (defun limitsimp (exp var)
682 (limitsimp-expt (sin-sq-cos-sq-sub exp) var))
684 ;; if var appears in base and power of expt,
685 ;; push var into power of of expt
686 (defun limitsimp-expt (exp var)
687 (cond ((or (atom exp)
688 (mnump exp)
689 (freeof var exp)) exp)
690 ((and (mexptp exp)
691 (not (freeof var (cadr exp)))
692 (not (freeof var (caddr exp))))
693 (m^ '$%e (simplify `((%log) ,exp))))
694 (t (subst0 (cons (cons (caar exp) ())
695 (mapcar #'(lambda (x)
696 (limitsimp-expt x var))
697 (cdr exp)))
698 exp))))
700 (defun gather-args-of (e fn x)
701 (cond (($mapatom e) nil)
702 ((and (eq fn (caar e)) (not (freeof x e))) (cdr e))
704 (remove-duplicates (reduce #'append
705 (mapcar #'(lambda (q)
706 (gather-args-of q fn x)) (cdr e))) :test #'alike1))))
708 ;; Replace every subexpression of e of the form cos(X)^2 + sin(X)^2, where X
709 ;; depends on x, by 1.
710 (defun sin-sq-cos-sq-sub (e &optional (x var))
711 (let ((ccc nil) (z) (ee))
712 (cond (($mapatom e) e)
713 ((mplusp e)
714 (setq ccc (gather-args-of e '%cos x))
715 (dolist (g ccc)
716 (setq z (gensym))
717 (setq ee (maxima-substitute z (power (ftake '%cos g) 2) e))
718 (setq ee (maxima-substitute (sub 1 z) (power (ftake '%sin g) 2) ee))
719 (when (freeof z (sratsimp ee))
720 (setq e ee)))
722 ;; maybe this isn't needed, but it's not wrong.
723 ((eq 'mqapply (caar e))
724 (subftake (caar (second e))
725 (mapcar #'(lambda (q) (sin-sq-cos-sq-sub q x)) (subfunsubs e))
726 (mapcar #'(lambda (q) (sin-sq-cos-sq-sub q x)) (subfunargs e))))
727 ;; map sin-sq-cos-sq-sub over the args
729 (fapply (caar e) (mapcar #'(lambda (q) (sin-sq-cos-sq-sub q x)) (cdr e)))))))
731 (defun expand-trigs (x var)
732 (cond ((atom x) x)
733 ((mnump x) x)
734 ((and (or (eq (caar x) '%sin)
735 (eq (caar x) '%cos))
736 (not (free (cadr x) var)))
737 ($trigexpand x))
738 ((member 'array (car x))
739 ;; Some kind of array reference. Return it.
741 (t (simplify (cons (ncons (caar x))
742 (mapcar #'(lambda (x)
743 (expand-trigs x var))
744 (cdr x)))))))
746 ;; The functionality of tansc has been blended into extra-simp, so we
747 ;; could orphan tansc. But extra-simp does more than tansc and tansc is
748 ;; called by the definite integration code and by the limit code. So we'll
749 ;; not orphan tansc.
750 (defun tansc (e)
751 (cond ((not (involve e
752 '(%cot %csc %binomial
753 %sec %coth %sech %csch
754 %acot %acsc %asec %acoth
755 %asech %acsch
756 %jacobi_ns %jacobi_nc %jacobi_cs
757 %jacobi_ds %jacobi_dc)))
759 (t (sratsimp (tansc1 e)))))
761 (defun tansc1 (e &aux tem)
762 (cond ((atom e) e)
763 ((and (setq e (cons (car e) (mapcar 'tansc1 (cdr e)))) ()))
764 ((setq tem (assoc (caar e) '((%cot . %tan) (%coth . %tanh)
765 (%sec . %cos) (%sech . %cosh)
766 (%csc . %sin) (%csch . %sinh)) :test #'eq))
767 (tansc1 (m^ (list (ncons (cdr tem)) (cadr e)) -1.)))
768 ((setq tem (assoc (caar e) '((%jacobi_nc . %jacobi_cn)
769 (%jacobi_ns . %jacobi_sn)
770 (%jacobi_cs . %jacobi_sc)
771 (%jacobi_ds . %jacobi_sd)
772 (%jacobi_dc . %jacobi_cd)) :test #'eq))
773 ;; Converts Jacobi elliptic function to its reciprocal
774 ;; function.
775 (tansc1 (m^ (list (ncons (cdr tem)) (cadr e) (third e)) -1.)))
776 ((setq tem (member (caar e) '(%sinh %cosh %tanh) :test #'eq))
777 (let (($exponentialize t))
778 (resimplify e)))
779 ((setq tem (assoc (caar e) '((%acsc . %asin) (%asec . %acos)
780 (%acot . %atan) (%acsch . %asinh)
781 (%asech . %acosh) (%acoth . %atanh)) :test #'eq))
782 (list (ncons (cdr tem)) (m^t (cadr e) -1.)))
783 ((and (eq (caar e) '%binomial) (among var (cdr e)))
784 (m// `((mfactorial) ,(cadr e))
785 (m* `((mfactorial) ,(m+t (cadr e) (m- (caddr e))))
786 `((mfactorial) ,(caddr e)))))
787 (t e)))
789 ;; Like TANSC but dependency on VAR is explicit. Use this instead of
790 ;; TANSC when possible.
791 (defun tansc-var (e var1)
792 (cond ((not (involve-var e var1
793 '(%cot %csc %binomial
794 %sec %coth %sech %csch
795 %acot %acsc %asec %acoth
796 %asech %acsch
797 %jacobi_ns %jacobi_nc %jacobi_cs
798 %jacobi_ds %jacobi_dc)))
801 (labels
802 ((tansc1-v (e &aux tem)
803 ;; Copy of TANSC1, but VAR replaced by VAR1
804 (cond ((atom e)
806 ((and (setq e (cons (car e) (mapcar #'tansc1-v (cdr e))))
807 ()))
808 ((setq tem (assoc (caar e)
809 '((%cot . %tan) (%coth . %tanh)
810 (%sec . %cos) (%sech . %cosh)
811 (%csc . %sin) (%csch . %sinh))
812 :test #'eq))
813 (tansc1-v (m^ (list (ncons (cdr tem)) (cadr e)) -1.)))
814 ((setq tem (assoc (caar e)
815 '((%jacobi_nc . %jacobi_cn)
816 (%jacobi_ns . %jacobi_sn)
817 (%jacobi_cs . %jacobi_sc)
818 (%jacobi_ds . %jacobi_sd)
819 (%jacobi_dc . %jacobi_cd))
820 :test #'eq))
821 ;; Converts Jacobi elliptic function to its reciprocal
822 ;; function.
823 (tansc1-v (m^ (list (ncons (cdr tem)) (cadr e) (third e))
824 -1.)))
825 ((setq tem (member (caar e) '(%sinh %cosh %tanh) :test #'eq))
826 (let (($exponentialize t))
827 (resimplify e)))
828 ((setq tem (assoc (caar e)
829 '((%acsc . %asin) (%asec . %acos)
830 (%acot . %atan) (%acsch . %asinh)
831 (%asech . %acosh) (%acoth . %atanh))
832 :test #'eq))
833 (list (ncons (cdr tem)) (m^t (cadr e) -1.)))
834 ((and (eq (caar e) '%binomial)
835 (among var1 (cdr e)))
836 (m// `((mfactorial) ,(cadr e))
837 (m* `((mfactorial) ,(m+t (cadr e) (m- (caddr e))))
838 `((mfactorial) ,(caddr e)))))
839 (t e))))
840 (sratsimp (tansc1-v e))))))
842 (defun hyperex (ex)
843 (cond ((not (involve ex '(%sin %cos %tan %asin %acos %atan
844 %sinh %cosh %tanh %asinh %acosh %atanh)))
846 (t (hyperex0 ex))))
848 (defun hyperex0 (ex)
849 (cond ((atom ex) ex)
850 ((eq (caar ex) '%sinh)
851 (m// (m+ (m^ '$%e (cadr ex)) (m- (m^ '$%e (m- (cadr ex)))))
853 ((eq (caar ex) '%cosh)
854 (m// (m+ (m^ '$%e (cadr ex)) (m^ '$%e (m- (cadr ex))))
856 ((and (member (caar ex)
857 '(%sin %cos %tan %asin %acos %atan %sinh
858 %cosh %tanh %asinh %acosh %atanh) :test #'eq)
859 (among var ex))
860 (hyperex1 ex))
861 (t (cons (car ex) (mapcar #'hyperex0 (cdr ex))))))
863 (defun hyperex1 (ex)
864 (resimplify ex))
866 ;;Used by tlimit also.
867 (defun limit1 (exp var val)
868 (prog ()
869 (let ((lhprogress? lhp?)
870 (lhp? ())
871 (ans ()))
872 (cond ((setq ans (and (not (atom exp)) (getlimval exp)))
873 (return ans))
874 ((and (not (infinityp val)) (setq ans (simplimsubst val exp)))
875 (return ans))
876 (t nil))
877 ;;;NUMDEN* => (values numerator denominator)
878 (multiple-value-bind (n dn)
879 (numden* exp)
880 (cond ((not (among var dn))
881 (return (simplimit (m// (simplimit n var val) dn) var val)))
882 ((not (among var n))
883 (return (simplimit (m* n (simplimexpt dn -1 (simplimit dn var val) -1)) var val)))
884 ((and lhprogress?
885 (/#alike n (car lhprogress?))
886 (/#alike dn (cdr lhprogress?)))
887 (throw 'lhospital nil)))
888 (return (limit2 n dn var val))))))
891 ;; If e/f is free of var (a special), return true. This code
892 ;; assumes that f is not zero. First, we test if e & f
893 ;; are alike--this check is relatively fast; second, we check
894 ;; if e/f is free of var.
895 (defun /#alike (e f)
896 (or (alike1 e f) (freeof var (sratsimp (div e f)))))
898 (defun limit2 (n dn var val)
899 (prog (n1 d1 lim-sign gcp sheur-ans)
900 (setq n (hyperex n) dn (hyperex dn))
901 (setq d1 (limit dn var val nil)
902 n1 (limit n var val nil))
903 (cond ((or (null n1) (null d1)) (return nil))
904 (t (setq n1 (sratsimp n1) d1 (sratsimp d1))))
905 (cond ((or (involve n '(mfactorial)) (involve dn '(mfactorial)))
906 (let ((ans (limfact2 n dn var val)))
907 (cond (ans (return ans))))))
908 (cond ((and (zerop2 n1) (zerop2 d1))
909 (cond ((not (equal (setq gcp (gcpower n dn)) 1))
910 (return (colexpt n dn gcp)))
911 ((and (real-epsilonp val)
912 (not (free n '%log))
913 (not (free dn '%log)))
914 (return (liminv (m// n dn))))
915 ((setq n1 (try-lhospital-quit n dn nil))
916 (return n1))))
917 ((and (zerop2 n1) (not (member d1 '($ind $und) :test #'eq))) (return 0))
918 ((zerop2 d1)
919 (setq n1 (ridofab n1))
920 (return (simplimtimes `(,n1 ,(simplimexpt dn -1 d1 -1))))))
921 (setq n1 (ridofab n1))
922 (setq d1 (ridofab d1))
923 (cond ((or (eq d1 '$und)
924 (and (eq n1 '$und) (not (real-infinityp d1))))
925 (return '$und))
926 ((eq d1 '$ind)
927 ;; At this point we have n1/$ind. Look if n1 is one of the
928 ;; infinities or zero.
929 (cond ((and (infinityp n1) (eq ($sign dn) '$pos))
930 (return n1))
931 ((and (infinityp n1) (eq ($sign dn) '$neg))
932 (return (simpinf (m* -1 n1))))
933 ((and (zerop1 n1)
934 (or (eq ($sign dn) '$pos)
935 (eq ($sign dn) '$neg)))
936 (return 0))
937 (t (return '$und))))
938 ((eq n1 '$ind) (return (cond ((infinityp d1) 0)
939 ((equal d1 0) '$und)
940 (t '$ind)))) ;SET LB
941 ((and (real-infinityp d1) (member n1 '($inf $und $minf) :test #'eq))
942 (cond ((and (not (atom dn)) (not (atom n))
943 (cond ((not (equal (setq gcp (gcpower n dn)) 1))
944 (return (colexpt n dn gcp)))
945 ((and (eq '$inf val)
946 (or (involve dn '(mfactorial %gamma))
947 (involve n '(mfactorial %gamma))))
948 (return (limfact n dn))))))
949 ((eq n1 d1) (setq lim-sign 1) (go cp))
950 (t (setq lim-sign -1) (go cp))))
951 ((and (infinityp d1) (infinityp n1))
952 (setq lim-sign (if (or (eq d1 '$minf) (eq n1 '$minf)) -1 1))
953 (go cp))
954 (t (return (simplimtimes `(,n1 ,(m^ d1 -1))))))
955 cp (setq n ($expand n) dn ($expand dn))
956 (cond ((mplusp n)
957 (let ((new-n (m+l (maxi (cdr n)))))
958 (cond ((not (alike1 new-n n))
959 (return (limit (m// new-n dn) var val 'think))))
960 (setq n1 new-n)))
961 (t (setq n1 n)))
962 (cond ((mplusp dn)
963 (let ((new-dn (m+l (maxi (cdr dn)))))
964 (cond ((not (alike1 new-dn dn))
965 (return (limit (m// n new-dn) var val 'think))))
966 (setq d1 new-dn)))
967 (t (setq d1 dn)))
968 (setq sheur-ans (sheur0 n1 d1))
969 (cond ((or (member sheur-ans '($inf $zeroa) :test #'eq)
970 (free sheur-ans var))
971 (return (simplimtimes `(,lim-sign ,sheur-ans))))
972 ((and (alike1 sheur-ans dn)
973 (not (mplusp n))))
974 ((member (setq n1 (cond ((expfactorp n1 d1) (expfactor n1 d1 var))
975 (t ())))
976 '($inf $zeroa) :test #'eq)
977 (return n1))
978 ((not (null (setq n1 (cond ((expfactorp n dn) (expfactor n dn var))
979 (t ())))))
980 (return n1))
981 ((and (alike1 sheur-ans dn) (not (mplusp n))))
982 ((not (alike1 sheur-ans (m// n dn)))
983 (return (simplimit (m// ($expand (m// n sheur-ans))
984 ($expand (m// dn sheur-ans)))
986 val))))
987 (cond ((and (not (and (eq val '$inf) (expp n) (expp dn)))
988 (setq n1 (try-lhospital-quit n dn nil))
989 (not (eq n1 '$und)))
990 (return n1)))
991 (throw 'limit t)))
993 ;; Test whether both n and dn have form
994 ;; product of poly^poly.
996 ;; It's important that both n and dn be free of extended real numbers
997 ;; (minf, zerob, ...), so we check for that too (see bug #4222).
998 (defun expfactorp (n dn)
999 (do ((llist (append (cond ((mtimesp n) (cdr n))
1000 (t (ncons n)))
1001 (cond ((mtimesp dn) (cdr dn))
1002 (t (ncons dn))))
1003 (cdr llist))
1004 (exp? t) ;IS EVERY ELEMENT SO FAR
1005 (factor nil)) ;A POLY^POLY?
1006 ((or (null llist)
1007 (not exp?))
1008 exp?)
1009 (setq factor (car llist))
1010 (setq exp?
1011 (and
1012 (not (amongl (list '$minf '$zerob '$zeroa '$ind '$und '$inf '$infinity) factor))
1013 (or (polyinx factor var ())
1014 (and (mexptp factor)
1015 (polyinx (cadr factor) var ())
1016 (polyinx (caddr factor) var ())))))))
1018 (defun expfactor (n dn var) ;Attempts to evaluate limit by grouping
1019 (prog (highest-deg) ; terms with similar exponents.
1020 (let ((new-exp (exppoly n))) ;exppoly unrats expon
1021 (setq n (car new-exp) ;and rtns deg of expons
1022 highest-deg (cdr new-exp)))
1023 (cond ((null n) (return nil))) ;nil means expon is not
1024 (let ((new-exp (exppoly dn))) ;a rat func.
1025 (setq dn (car new-exp)
1026 highest-deg (max highest-deg (cdr new-exp))))
1027 (cond ((or (null dn)
1028 (= highest-deg 0)) ; prevent infinite recursion
1029 (return nil)))
1030 (return
1031 (do ((answer 1)
1032 (degree highest-deg (1- degree))
1033 (numerator n)
1034 (denominator dn)
1035 (numfactors nil)
1036 (denfactors nil))
1037 ((= degree -1)
1038 (m* answer
1039 (limit (m// numerator denominator)
1042 'think)))
1043 (let ((newnumer-factor (get-newexp&factors
1044 numerator
1045 degree
1046 var)))
1047 (setq numerator (car newnumer-factor)
1048 numfactors (cdr newnumer-factor)))
1049 (let ((newdenom-factor (get-newexp&factors
1050 denominator
1051 degree
1052 var)))
1053 (setq denominator (car newdenom-factor)
1054 denfactors (cdr newdenom-factor)))
1055 (setq answer (simplimit (list '(mexpt)
1056 (m* answer
1057 (m// numfactors denfactors))
1058 (cond ((> degree 0) var)
1059 (t 1)))
1061 val))
1062 (cond ((member answer '($ind $und) :test #'equal)
1063 ;; cannot handle limit(exp(x*%i)*x, x, inf);
1064 (return nil))
1065 ((member answer '($inf $minf) :test #'equal)
1066 ;; 0, zeroa, zerob are passed through to next iteration
1067 (return (simplimtimes (list (m// numerator denominator) answer)))))))))
1069 (defun exppoly (exp) ;RETURNS EXPRESSION WITH UNRATTED EXPONENTS
1070 (do ((factor nil)
1071 (highest-deg 0)
1072 (new-exp 1)
1073 (exp (cond ((mtimesp exp)
1074 (cdr exp))
1075 (t (ncons exp)))
1076 (cdr exp)))
1077 ((null exp) (cons new-exp highest-deg))
1078 (setq factor (car exp))
1079 (setq new-exp
1080 (m* (cond ((or (not (mexptp factor))
1081 (not (ratp (caddr factor) var)))
1082 factor)
1083 (t (setq highest-deg
1084 (max highest-deg
1085 (ratdegree (caddr factor))))
1086 (m^ (cadr factor) (unrat (caddr factor)))))
1087 new-exp))))
1089 (defun unrat (exp) ;RETURNS UNRATTED EXPRESION
1090 (multiple-value-bind (n d)
1091 (numden* exp)
1092 (let ((tem ($divide n d)))
1093 (m+ (cadr tem)
1094 (m// (caddr tem) d)))))
1096 (defun get-newexp&factors (exp degree var) ;RETURNS (CONS NEWEXP FACTORS)
1097 (do ((terms (cond ((mtimesp exp)(cdr exp)) ; SUCH THAT
1098 (t (ncons exp))) ; NEWEXP*FACTORS^(VAR^DEGREE)
1099 (cdr terms)) ; IS EQUAL TO EXP.
1100 (factors 1)
1101 (newexp 1)
1102 (factor nil))
1103 ((null terms)
1104 (cons newexp
1105 factors))
1106 (setq factor (car terms))
1107 (cond ((not (mexptp factor))
1108 (cond ((= degree 0)
1109 (setq factors (m* factor factors)))
1110 (t (setq newexp (m* factor newexp)))))
1111 ((or (= degree -1)
1112 (= (ratdegree (caddr factor))
1113 degree))
1114 (setq factors (m* (m^ (cadr factor)
1115 (leading-coef (caddr factor)))
1116 factors)
1117 newexp (m* (m^ (cadr factor)
1118 (m- (caddr factor)
1119 (m* (leading-coef (caddr factor))
1120 (m^ var degree))))
1121 newexp)))
1122 (t (setq newexp (m* factor newexp))))))
1124 (defun leading-coef (rat)
1125 (ratlim (m// rat (m^ var (ratdegree rat)))))
1127 (defun ratdegree (rat)
1128 (multiple-value-bind (n d)
1129 (numden* rat)
1130 (- (deg n) (deg d))))
1132 (defun limfact2 (n d var val)
1133 (let ((n1 (reflect0 n var val))
1134 (d1 (reflect0 d var val)))
1135 (cond ((and (alike1 n n1)
1136 (alike1 d d1))
1137 nil)
1138 (t (limit (m// n1 d1) var val 'think)))))
1140 ;; takes expression and returns operator at front with all flags removed
1141 ;; except array flag.
1142 ;; array flag must match for alike1 to consider two things to be the same.
1143 ;; ((MTIMES SIMP) ... ) => (MTIMES)
1144 ;; ((PSI SIMP ARRAY) 0) => (PSI ARRAY)
1145 (defun operator-with-array-flag (exp)
1146 (cond ((member 'array (car exp) :test #'eq)
1147 (list (caar exp) 'array))
1148 (t (list (caar exp)))))
1150 (defun reflect0 (exp var val)
1151 (cond ((atom exp) exp)
1152 ((and (eq (caar exp) 'mfactorial)
1153 (let ((argval (limit (cadr exp) var val 'think)))
1154 (or (eq argval '$minf)
1155 (and (numberp argval)
1156 (> 0 argval)))))
1157 (reflect (cadr exp)))
1158 (t (cons (operator-with-array-flag exp)
1159 (mapcar (function
1160 (lambda (term)
1161 (reflect0 term var val)))
1162 (cdr exp))))))
1164 (defun reflect (arg)
1165 (m* -1
1166 '$%pi
1167 (m^ (list (ncons 'mfactorial)
1168 (m+ -1
1169 (m* -1 arg)))
1171 (m^ (list (ncons '%sin)
1172 (m* '$%pi arg))
1173 -1)))
1175 (defun limfact (n d)
1176 (let ((ans ()))
1177 (setq n (stirling0 n)
1178 d (stirling0 d))
1179 (setq ans (toplevel-$limit (m// n d) var '$inf))
1180 (cond ((and (atom ans)
1181 (not (member ans '(und ind ) :test #'eq))) ans)
1182 ((eq (caar ans) '%limit) ())
1183 (t ans))))
1185 ;; substitute asymptotic approximations for gamma, factorial, and
1186 ;; polylogarithm
1187 (defun stirling0 (e)
1188 (cond ((atom e) e)
1189 ((and (setq e (cons (car e) (mapcar 'stirling0 (cdr e))))
1190 nil))
1191 ((eq (caar e) '%gamma)
1192 (let ((ans (limit (cadr e) var val 'think)))
1193 (cond ((memq ans '($inf $minf $infinity))
1194 (stirling (cadr e)))
1195 ((eq ans '$zeroa)
1196 (add (div 1 (cadr e)) (mul -1 '$%gamma)))
1197 ((and (integerp ans) (< ans 0))
1198 (div (if (oddp ans) -1 1)
1199 (mul (ftake 'mfactorial (mul -1 ans)) (sub (cadr e) ans))))
1200 (t (ftake '%gamma (cadr e))))))
1202 ((eq (caar e) 'mfactorial)
1203 (let ((n (limit (cadr e) var val 'think)))
1204 (cond ((eq n '$inf)
1205 (stirling (add 1 (cadr e))))
1206 ((and (integerp n) (< n 0))
1207 (setq n (mul -1 n))
1208 (div (if (oddp n) 1 -1)
1209 (mul (ftake 'mfactorial (sub n 1)) (add var n))))
1210 (t e))))
1211 ((and (eq (caar e) 'mqapply) ;; polylogarithm
1212 (eq (subfunname e) '$li)
1213 (let ((arglim (limit (car (subfunargs e)) var val 'think)))
1214 (or (eq arglim '$inf) (eq arglim '$minf)))
1215 (integerp (car (subfunsubs e))))
1216 (li-asymptotic-expansion (m- (car (subfunsubs e)) 1)
1217 (car (subfunsubs e))
1218 (car (subfunargs e))))
1219 (t e)))
1221 (defun stirling (x)
1222 "Return sqrt(2*%pi/x)*(x/%e)^x, the Stirling approximation of
1223 gamma(x). The argument x can be any valid expression."
1224 (mul (power (div (mul 2 '$%pi) x)
1225 1//2)
1226 (power (div x '$%e)
1227 x)))
1229 (defun no-err-sub (v e &aux ans)
1230 (let ((errorsw t) (*zexptsimp? t)
1231 (errcatch t)
1232 ;; Don't print any error messages
1233 ($errormsg nil))
1234 ;; Should we just use IGNORE-ERRORS instead HANDLER-CASE here? I
1235 ;; (rtoy) am choosing the latter so that unexpected errors will
1236 ;; actually show up instead of being silently discarded.
1237 (handler-case
1238 (setq ans (catch 'errorsw
1239 (ignore-rat-err
1240 (sratsimp (subin v e)))))
1241 (maxima-$error ()
1242 (setq ans nil)))
1243 (cond ((null ans) t) ; Ratfun package returns NIL for failure.
1244 (t ans))))
1246 ;; Like NO-ERR-SUB but dependency on VAR is explicit. Use this
1247 ;; instead when possible.
1248 (defun no-err-sub-var (v e var1 &aux ans)
1249 (let ((errorsw t) (*zexptsimp? t)
1250 (errcatch t)
1251 ;; Don't print any error messages
1252 ($errormsg nil))
1253 ;; Should we just use IGNORE-ERRORS instead HANDLER-CASE here? I
1254 ;; (rtoy) am choosing the latter so that unexpected errors will
1255 ;; actually show up instead of being silently discarded.
1256 (handler-case
1257 (setq ans (catch 'errorsw
1258 (ignore-rat-err
1259 (sratsimp (subin-var v e var1)))))
1260 (maxima-$error ()
1261 (setq ans nil)))
1262 (cond ((null ans) t) ; Ratfun package returns NIL for failure.
1263 (t ans))))
1265 (defun simplim%mabs (e x pt)
1266 (let ((lim (limit (cadr e) x pt 'think)))
1267 (cond ((or (eq lim '$zeroa) (eql lim 0) (eq lim '$ind)) lim)
1268 ((eq lim '$zerob) '$zeroa)
1269 ((eq lim '$und) (throw 'limit nil))
1270 ((or (eq lim '$minf) (eq lim '$inf) (eq lim '$infinity)) '$inf)
1271 (t (ftake 'mabs lim)))))
1272 (setf (get 'mabs 'simplim%function) 'simplim%mabs)
1274 (defun extended-real-p (e)
1275 (member e (list '$minf '$zerob '$zeroa '$ind '$und '$inf '$infinity)))
1277 ;; Evaluate the limit of e as var (special) approaches v using direct substitution.
1278 ;; This function is the last of the chain of methods tried by limit. As such it
1279 ;; shouldn't call higher level functions such as simplimit or limit--doing so
1280 ;; would risk creating an infinite loop.
1282 ;; This function special cases sums, products, and powers. It declines to use
1283 ;; direct substitution on any expression whose main operator has a simplim%function
1284 ;; function. Generally, limits of functions that have a simplim%function should be
1285 ;; handled by those specialized functions, not by simplimsubst. Having said this,
1286 ;; it's OK for simplimsubst to special case an operator and do direct substitution
1287 ;; when its OK. The cases of log, cosine, and sine happen often enough that these
1288 ;; functions are special cased.
1290 ;; Possibly simplimsubst should decline to do direct substitution on functions
1291 ;; that have a limit function, for example inverse_jacobi_ns.
1293 ;; For all other kinds of expressions, this function assumes that if substitution
1294 ;; doesn't result in an error (division by zero, for example), the function
1295 ;; is continuous at the limit point. That's dodgy. This dodginess underscores the
1296 ;; need to define a simplim%function functions that are not continuous on their
1297 ;; domains.
1299 ;; This function sometimes receives an un-simplified expression. Maybe they should be
1300 ;; simplified, maybe not.
1302 ;; Locally setting $numer and $%enumer to nil keeps some limits, for example
1303 ;; limit(sin(x)/x,x,0) from returning 1.0 when numer is true. (Barton Willis)
1305 (defun simplimsubst (v e)
1306 (let ((ans nil) ($numer nil) ($%enumer nil) (ee))
1307 (cond
1308 ;; When e is a number, return it.
1309 (($numberp e) e)
1310 ;; When e is a mapatom, substitute v for var and return.
1311 (($mapatom e) ($substitute v var e))
1312 ;; Special case mexpt expressions. Decline direct substitution for
1313 ;; extended reals.
1314 ((and (mexptp e) (not (extended-real-p v)))
1315 (let ((x (simplimsubst v (second e)))
1316 (n (simplimsubst v (third e))))
1317 ;; Decline direct substitution (DS) for 0^negative. Also decline
1318 ;; DS when x is on the negative real axis and n isn't an integer.
1319 ;; Additionally, we require that DS is OK for both x & n.
1320 (if (and x n (not (and (zerop2 x) (eq t (mgqp 0 n)))) ; not 0^negative
1321 (or (off-negative-real-axisp x) (integerp n)))
1322 (ftake 'mexpt x n) nil)))
1323 ;; Special case product and sum expressions. Again, we decline direct
1324 ;; substitution for extended reals.
1325 ((and (or (mplusp e) (mtimesp e)) (not (extended-real-p v)))
1326 (setq ee (mapcar #'(lambda(q) (simplimsubst v q)) (cdr e)))
1327 (if (some #'(lambda (q) (eq q nil)) ee) nil
1328 (simplifya (cons (list (caar e)) ee) t)))
1329 ;; Decline direct substitution for sums, products, and powers for
1330 ;; the extended real case.
1331 ((and (or (mexptp e) (mplusp e) (mtimesp e)) (extended-real-p v))
1332 nil)
1333 ;; Special case log expressions--possibly the log case happens
1334 ;; often enough to make this worthwhile.
1335 ((and (consp e) (consp (car e)) (eq '%log (caar e)))
1336 (let ((w (simplimsubst v (cadr e))))
1337 (if (and w (off-negative-real-axisp w)) (ftake '%log w) nil)))
1338 ;; Special case %cos and %sin expressions--we could special case others.
1339 ;; The lenient-realp check declines direct substitution for complex arguments--
1340 ;; this check could be relaxed.
1341 ((and (consp e) (consp (car e)) (or (member (caar e) (list '%cos '%sin))))
1342 (let ((op (caar e)))
1343 (setq e (simplimsubst v (second e)))
1344 (if (and e (lenient-realp e) (not (extended-real-p e))) (ftake op e) nil)))
1345 ;; Don't use direct substitution on expressions whose main operator has
1346 ;; a simplim%function.
1347 ((and (consp e) (consp (car e)) (get (caar e) 'simplim%function)) nil)
1348 ;; The function no-err-sub returns true when there is an error
1349 ((not (eq t (setq ans (no-err-sub (ridofab v) e))))
1350 ;; Previously the condition (zerop2 ans) was (=0 ($radcan ans)). In
1351 ;; December 2021, the testsuite + the share testsuite only gives ans = 0,
1352 ;; making the radcan unneeded.
1353 (cond ((and (member v '($zeroa $zerob) :test #'eq) (zerop2 ans))
1354 (setq ans (behavior e var v))
1355 (cond ((eql ans 1) '$zeroa)
1356 ((eql ans -1) '$zerob)
1357 (t nil))) ;behavior can't find direction
1358 (t ans)))
1359 ;; direct substitution fails, so return nil.
1360 (t nil))))
1362 ;;;returns (cons numerator denominator)
1363 (defun numden* (e)
1364 (let ((e (factor (simplify e)))
1365 (numer ())
1366 (denom ()))
1367 (cond ((atom e)
1368 (push e numer))
1369 ((mtimesp e)
1370 (mapc #'forq (cdr e)))
1372 (forq e)))
1373 (cond ((null numer)
1374 (setq numer 1))
1375 ((null (cdr numer))
1376 (setq numer (car numer)))
1378 (setq numer (m*l numer))))
1379 (cond ((null denom)
1380 (setq denom 1))
1381 ((null (cdr denom))
1382 (setq denom (car denom)))
1384 (setq denom (m*l denom))))
1385 (values (factor numer) (factor denom))))
1387 ;;;FACTOR OR QUOTIENT
1388 ;;;Setq's the special vars numer and denom from numden*
1389 (defun forq (e)
1390 (cond ((and (mexptp e)
1391 (not (freeof var e))
1392 (null (pos-neg-p (caddr e))))
1393 (push (m^ (cadr e) (m* -1. (caddr e))) denom))
1394 (t (push e numer))))
1396 ;;;Predicate to tell whether an expression is pos,zero or neg as var -> val.
1397 ;;;returns T if pos,zero. () if negative or don't know.
1398 (defun pos-neg-p (exp)
1399 (let ((ans (limit exp var val 'think)))
1400 (cond ((and (not (member ans '($und $ind $infinity) :test #'eq))
1401 (equal ($imagpart ans) 0))
1402 (let ((sign (getsignl ans)))
1403 (cond ((or (equal sign 1)
1404 (equal sign 0))
1406 ((equal sign -1) nil))))
1407 (t 'unknown))))
1409 (declare-top (unspecial n dn))
1411 (defun expp (e)
1412 (cond ((radicalp e var) nil)
1413 ((member (caar e) '(%log %sin %cos %tan %sinh %cosh %tanh mfactorial
1414 %asin %acos %atan %asinh %acosh %atanh) :test #'eq) nil)
1415 ((simplexp e) t)
1416 ((do ((e (cdr e) (cdr e)))
1417 ((null e) nil)
1418 (and (expp (car e)) (return t))))))
1420 (defun simplexp (e)
1421 (and (mexptp e)
1422 (radicalp (cadr e) var)
1423 (among var (caddr e))
1424 (radicalp (caddr e) var)))
1427 (defun gcpower (a b)
1428 ($gcd (getexp a) (getexp b)))
1430 (defun getexp (exp)
1431 (cond ((and (mexptp exp)
1432 (free (caddr exp) var)
1433 (eq (ask-integer (caddr exp) '$integer) '$yes))
1434 (caddr exp))
1435 ((mtimesp exp) (getexplist (cdr exp)))
1436 (t 1)))
1438 (defun getexplist (list)
1439 (cond ((null (cdr list))
1440 (getexp (car list)))
1441 (t ($gcd (getexp (car list))
1442 (getexplist (cdr list))))))
1444 (defun limroot (exp power)
1445 (cond ((or (atom exp) (not (member (caar exp) '(mtimes mexpt) :test #'eq)))
1446 (limroot (list '(mexpt) exp 1) power)) ;This is strange-JIM.
1447 ((mexptp exp) (m^ (cadr exp)
1448 (sratsimp (m* (caddr exp) (m^ power -1.)))))
1449 (t (m*l (mapcar #'(lambda (x)
1450 (limroot x power))
1451 (cdr exp))))))
1453 ;;NUMERATOR AND DENOMINATOR HAVE EXPONENTS WITH GCD OF GCP.
1454 ;;; Used to call simplimit but some of the transformations used here
1455 ;;; were not stable w.r.t. the simplifier, so try keeping exponent separate
1456 ;;; from bas.
1458 (defun colexpt (n dn gcp)
1459 (let ((bas (m* (limroot n gcp) (limroot dn (m* -1 gcp))))
1460 (expo gcp)
1461 baslim expolim)
1462 (setq baslim (limit bas var val 'think))
1463 (setq expolim (limit expo var val 'think))
1464 (simplimexpt bas expo baslim expolim)))
1466 ;; this function is responsible for the following bug:
1467 ;; limit(x^2 + %i*x, x, inf) -> inf (should be infinity)
1468 (defun ratlim (e)
1469 (setq e (sratsimp ($trigreduce e)))
1470 (cond ((member val '($inf $infinity) :test #'eq)
1471 (setq e (maxima-substitute (m^t 'x -1) var e)))
1472 ((eq val '$minf)
1473 (setq e (maxima-substitute (m^t -1 (m^t 'x -1)) var e)))
1474 ((eq val '$zerob)
1475 (setq e (maxima-substitute (m- 'x) var e)))
1476 ((eq val '$zeroa)
1477 (setq e (maxima-substitute 'x var e)))
1478 ((setq e (maxima-substitute (m+t 'x val) var e))))
1479 (destructuring-let* ((e (let (($ratfac ()))
1480 ($rat (sratsimp e) 'x)))
1481 ((h n . d) e)
1482 (g (genfind h 'x))
1483 (nd (lodeg n g))
1484 (dd (lodeg d g)))
1485 (cond ((and (setq e
1486 (subst var
1488 (sratsimp (m// ($ratdisrep `(,h ,(locoef n g) . 1))
1489 ($ratdisrep `(,h ,(locoef d g) . 1))))))
1490 (> nd dd))
1491 (cond ((not (member val '($zerob $zeroa $inf $minf) :test #'eq))
1493 ((not (equal ($imagpart e) 0))
1495 ((null (setq e (getsignl ($realpart e))))
1497 ((equal e 1) '$zeroa)
1498 ((equal e -1) '$zerob)
1499 (t 0)))
1500 ((equal nd dd) e)
1501 ((not (member val '($zerob $zeroa $infinity $inf $minf) :test #'eq))
1502 (throw 'limit t))
1503 ((eq val '$infinity) '$infinity)
1504 ((not (equal ($imagpart e) 0)) '$infinity)
1505 ((null (setq e (getsignl ($realpart e))))
1506 (throw 'limit t))
1507 ((equal e 1) '$inf)
1508 ((equal e -1) '$minf)
1509 (t 0))))
1511 (defun lodeg (n x)
1512 (if (or (atom n) (not (eq (car n) x)))
1514 (lowdeg (cdr n))))
1516 (defun locoef (n x)
1517 (if (or (atom n) (not (eq (car n) x)))
1519 (car (last n))))
1521 ;; This function tries to determine the increasing/decreasing
1522 ;; behavior of an expression exp with respect to some variable var.
1523 ;; val determines the mode:
1524 ;; - $zeroa: From "positive zero" towards the right
1525 ;; - $zerob: From "negative zero" towards the left
1526 ;; - $inf: From "positive infinity" towards the left
1527 ;; - $minf: From "negative infinity" towards the right
1528 ;; Return values are -1 (decreasing), +1 (increasing) or 0 (don't know).
1529 (defun behavior (exp var val)
1530 ;; $inf/$minf is handled by substituting 1/var for var
1531 ;; and setting val to $zeroa/$zerob.
1532 (cond ((real-infinityp val)
1533 (setq val (cond
1534 ((eq val '$inf) '$zeroa)
1535 ((eq val '$minf) '$zerob))
1536 exp (sratsimp (subin (m^ var -1) exp)))))
1537 (cond
1538 ((not (member val '($zeroa $zerob $inf $minf)))
1540 ;; Shortcut for constants.
1541 ((freeof var exp)
1543 ;; Shortcut for the variable itself.
1544 ((eq exp var)
1545 (if (member val '($zeroa $minf) :test #'eq) 1 -1))
1546 ;; This limits the recursion depth of the function.
1547 ;; Before giving up, always try behavior-by-diff, which doesn't recurse.
1548 ((= *behavior-count-now* +behavior-count+)
1549 (behavior-by-diff exp var val))
1551 (let ((*behavior-count-now* (1+ *behavior-count-now*)) pair sign ans)
1552 (cond
1553 ;; Pull out constant factors with known signs from a product:
1554 ;; behavior(c * f(x)) = signum(c) * behavior(f(x))
1555 ((and (mtimesp exp)
1556 (prog2 (setq pair (partition exp var 1))
1557 (not (equal (car pair) 1))))
1558 (setq sign (getsignl (car pair)))
1559 (if (not (fixnump sign))
1561 (mul sign (behavior (cdr pair) var val))))
1562 ;; Pull out constant terms from a sum:
1563 ;; behavior(c + f(x)) = behavior(f(x))
1564 ((and (mplusp exp)
1565 (prog2 (setq pair (partition exp var 0))
1566 (not (equal (car pair) 0))))
1567 (behavior (cdr pair) var val))
1568 ;; Handle f(x)^c for the case f(0) = 0 and c > 0
1569 ;; (probably other cases could be handled, too)
1570 ((and (mexptp exp)
1571 (free (caddr exp) var)
1572 (=0 (no-err-sub 0 exp))
1573 (equal (getsignl (caddr exp)) 1)
1574 (not (equal 0 (setq ans (behavior-expt (cadr exp) (caddr exp))))))
1575 ans)
1576 ;; Handle 1 / f(x):
1577 ;; behavior(1 / f(x)) = -behavior(f(x))
1578 ((equal ($num exp) 1)
1579 (- (behavior ($denom exp) var val)))
1580 ;; Handle c^f(x) for c > 1:
1581 ;; behavior(c^f(x)) = behavior(f(x))
1582 ((and (mexptp exp)
1583 (free (cadr exp) var)
1584 (equal 1 (getsignl (m- (cadr exp) 1)))
1585 (not (equal 0 (setq ans (behavior (caddr exp) var val)))))
1586 ans)
1587 ;; Handle c^f(x) for 0 < c < 1:
1588 ;; behavior(c^f(x)) = -behavior(f(x))
1589 ((and (mexptp exp)
1590 (free (cadr exp) var)
1591 (equal 1 (getsignl (cadr exp)))
1592 (equal -1 (getsignl (m- (cadr exp) 1)))
1593 (not (equal 0 (setq ans (behavior (caddr exp) var val)))))
1594 (- ans))
1595 ;; atan, erf, sinh and tanh are monotonically increasing,
1596 ;; so their behavior is equal to the behavior of their arguments.
1597 ;; behavior(monotonically_increasing(f(x))) = behavior(f(x))
1598 ((member (caar exp) '(%atan %erf %sinh %tanh) :test #'eq)
1599 (behavior (cadr exp) var val))
1600 ;; Similarly, acot is monotonically decreasing left and right of x = 0.
1601 ;; The singularity doesn't matter for our purposes.
1602 ;; behavior(monotonically_decreasing(f(x))) = -behavior(f(x))
1603 ((eq (caar exp) '%acot)
1604 (- (behavior (cadr exp) var val)))
1605 ;; Note: More functions could be added here.
1606 ;; Ideally, use properties defined on the functions.
1607 ;; Handle log(f(x)) for f(0) = 0:
1608 ;; If behavior(f(x)) = 1, then behavior(log(f(x))) = 1
1609 ((and (mlogp exp)
1610 (=0 (no-err-sub 0 (cadr exp)))
1611 (equal 1 (behavior (cadr exp) var val)))
1613 ;; Try to determine the behavior by taking the derivative.
1614 ((not (equal 0 (setq ans (behavior-by-diff exp var val))))
1615 ans)
1616 ;; If exp is a sum and all terms have the same behavior, return that.
1617 ;; The sum of increasing functions is increasing.
1618 ;; The sum of decreasing functions is decreasing.
1619 ((and (mplusp exp)
1620 (not (equal 0 (setq ans (behavior-all-same exp var val)))))
1621 ans)
1622 (t 0))))))
1624 (defun behavior-all-same (exp var val)
1625 (let* ((exps (cdr exp)) (first-behavior (behavior (first exps) var val)))
1626 (if (or (equal first-behavior 0)
1627 (not (every #'(lambda (exp) (equal (behavior exp var val) first-behavior))
1628 (rest exps))))
1630 first-behavior)))
1632 (defun behavior-expt (bas expo)
1633 (let ((behavior (behavior bas var val)))
1634 (cond ((= behavior 1) 1)
1635 ((= behavior 0) 0)
1636 ((eq (ask-integer expo '$integer) '$yes)
1637 (cond ((eq (ask-integer expo '$even) '$yes) 1)
1638 (t behavior)))
1639 ((ratnump expo)
1640 (cond ((evenp (cadr expo)) 1)
1641 ((oddp (caddr expo)) behavior)
1642 (t 0)))
1643 (t 0))))
1645 (defun behavior-by-diff (exp var val)
1646 (do ((ct 0 (1+ ct))
1647 (exp (sratsimp (sdiff exp var)) (sratsimp (sdiff exp var)))
1648 (n () (not n))
1649 (ans ())) ; This do wins by a return.
1650 ((> ct 1) 0) ; This loop used to run up to 5 times,
1651 ;; but the size of some expressions would blow up.
1652 (setq ans (no-err-sub 0 exp)) ;Why not do an EVENFN and ODDFN
1653 ;test here.
1654 (cond ((eq ans t)
1655 (return 0))
1656 ((=0 ans) ()) ;Do it again.
1657 (t (setq ans (getsignl ans))
1658 (cond (n (return ans))
1659 ((equal ans 1)
1660 (return (if (eq val '$zeroa) 1 -1)))
1661 ((equal ans -1)
1662 (return (if (eq val '$zeroa) -1 1)))
1663 (t (return 0)))))))
1665 (defun try-lhospital (n d ind)
1666 ;;Make one catch for the whole bunch of lhospital trials.
1667 (let ((ans (lhospital-catch n d ind)))
1668 (cond ((null ans) ())
1669 ((not (free-infp ans)) (simpinf ans))
1670 ((not (free-epsilonp ans)) (simpab ans))
1671 (t ans))))
1673 (defun try-lhospital-quit (n d ind)
1674 (let ((ans (or (lhospital-catch n d ind)
1675 (lhospital-catch (m^ d -1) (m^ n -1) ind))))
1676 (cond ((null ans) (throw 'limit t))
1677 ((not (free-infp ans)) (simpinf ans))
1678 ((not (free-epsilonp ans)) (simpab ans))
1679 (t ans))))
1681 (defun lhospital-catch (n d ind)
1682 (cond ((> 0 lhcount)
1683 (setq lhcount $lhospitallim)
1684 (throw 'lhospital nil))
1685 ((equal lhcount $lhospitallim)
1686 (let ((lhcount (m+ lhcount -1)))
1687 (catch 'lhospital (lhospital n d ind))))
1688 (t (setq lhcount (m+ lhcount -1))
1689 (prog1 (lhospital n d ind)
1690 (setq lhcount (m+ lhcount 1))))))
1691 ;;If this succeeds then raise LHCOUNT.
1694 (defun lhospital (n d ind)
1695 (declare (special val lhp?))
1696 (when (mtimesp n)
1697 (setq n (m*l (mapcar #'(lambda (term) (lhsimp term var val)) (cdr n)))))
1698 (when (mtimesp d)
1699 (setq d (m*l (mapcar #'(lambda (term) (lhsimp term var val)) (cdr d)))))
1700 (multiple-value-bind (n d)
1701 (lhop-numden n d)
1702 (let (const nconst dconst)
1703 (setq lhp? (and (null ind) (cons n d)))
1704 (multiple-value-setq (nconst n) (var-or-const n))
1705 (multiple-value-setq (dconst d) (var-or-const d))
1707 (setq n (stirling0 n)) ;; replace factorial and %gamma
1708 (setq d (stirling0 d)) ;; with approximations
1710 (setq n (sdiff n var) ;; take derivatives for l'hospital
1711 d (sdiff d var))
1713 (if (or (not (free n '%derivative)) (not (free d '%derivative)))
1714 (throw 'lhospital ()))
1715 (let (($trigexpandtimes nil)) ;see #895 limit x->inf sin(100/x)*x very slow
1716 (setq n (expand-trigs (tansc n) var))
1717 (setq d (expand-trigs (tansc d) var)))
1719 (multiple-value-setq (const n d) (remove-singularities n d))
1720 (setq const (m* const (m// nconst dconst)))
1721 (simpinf (let ((ans (if ind
1722 (limit2 n d var val)
1723 (limit-numden n d val))))
1724 ;; When the limit function returns, it's possible that it will return NIL
1725 ;; (gave up without finding a limit). It's also possible that it will
1726 ;; return something containing UND. We treat that as a failure too.
1727 (when (and ans (freeof '$und ans))
1728 (sratsimp (m* const ans))))))))
1730 ;; Try to compute the limit of a quotient NUM/DEN, trying to massage the input
1731 ;; into a convenient form for LIMIT on the way.
1732 (defun limit-numden (n d val)
1733 (let ((expr (cond
1734 ;; For general arguments, the best approach seems to be to use
1735 ;; sratsimp to simplify the quotient as much as we can, then
1736 ;; $multthru, which splits it up into a sum (presumably useful
1737 ;; because limit(a+b) = limit(a) + limit(b) if the limits exist, and
1738 ;; the right hand side might be easier to calculate)
1739 ((not (mplusp n))
1740 ($multthru (sratsimp (m// n d))))
1742 ;; If we've already got a sum in the numerator, it seems to be
1743 ;; better not to recombine it. Call LIMIT on the whole lot, though,
1744 ;; because terms with infinite limits might cancel to give a finite
1745 ;; result.
1747 (m+l (mapcar #'(lambda (x)
1748 (sratsimp (m// x d)))
1749 (cdr n)))))))
1751 (limit expr var val 'think)))
1753 ;; Heuristics for picking the right way to express a LHOSPITAL problem.
1754 (defun lhop-numden (num denom)
1755 (declare (special var))
1756 (cond ((let ((log-num (involve num '(%log))))
1757 (cond ((null log-num) ())
1758 ((lessthan (num-of-logs (factor (sratsimp (sdiff (m^ num -1) var))))
1759 (num-of-logs (factor (sratsimp (sdiff num var)))))
1760 (psetq num (m^ denom -1) denom (m^ num -1))
1762 (t t))))
1763 ((let ((log-denom (involve denom '(%log))))
1764 (cond ((null log-denom) ())
1765 ((lessthan (num-of-logs (sratsimp (sdiff (m^ denom -1) var)))
1766 (num-of-logs (sratsimp (sdiff denom var))))
1767 (psetq denom (m^ num -1) num (m^ denom -1))
1769 (t t))))
1770 ((let ((exp-num (%einvolve num)))
1771 (cond (exp-num
1772 (cond ((%e-right-placep exp-num)
1774 (t (psetq num (m^ denom -1)
1775 denom (m^ num -1)) t)))
1776 (t ()))))
1777 ((let ((exp-den (%einvolve denom)))
1778 (cond (exp-den
1779 (cond ((%e-right-placep exp-den)
1781 (t (psetq num (m^ denom -1)
1782 denom (m^ num -1)) t)))
1783 (t ()))))
1784 ((let ((scnum (involve num '(%sin))))
1785 (cond (scnum (cond ((trig-right-placep '%sin scnum) t)
1786 (t (psetq num (m^ denom -1)
1787 denom (m^ num -1)) t)))
1788 (t ()))))
1789 ((let ((scden (involve denom '(%sin))))
1790 (cond (scden (cond ((trig-right-placep '%sin scden) t)
1791 (t (psetq num (m^ denom -1)
1792 denom (m^ num -1)) t)))
1793 (t ()))))
1794 ((let ((scnum (involve num '(%asin %acos %atan))))
1795 ;; If the numerator contains an inverse trig and the
1796 ;; denominator or reciprocal of denominator is polynomial,
1797 ;; leave everything as is. If the inverse trig is moved to
1798 ;; the denominator, things get messy, even if the numerator
1799 ;; becomes a polynomial. This is not perfect.
1800 (cond ((and scnum (or (polyinx denom var ())
1801 (polyinx (m^ denom -1) var ())))
1803 (t nil))))
1804 ((or (oscip num) (oscip denom)))
1805 ((frac num)
1806 (psetq num (m^ denom -1) denom (m^ num -1))))
1807 (values num denom))
1809 ;;i don't know what to do here for some cases, may have to be refined.
1810 (defun num-of-logs (exp)
1811 (cond ((mapatom exp) 0)
1812 ((equal (caar exp) '%log)
1813 (m+ 1 (num-of-log-l (cdr exp))))
1814 ((and (mexptp exp) (mnump (caddr exp)))
1815 (m* (simplify `((mabs) ,(caddr exp)))
1816 (num-of-logs (cadr exp))))
1817 (t (num-of-log-l (cdr exp)))))
1819 (defun num-of-log-l (llist)
1820 (do ((temp llist (cdr temp)) (ans 0))
1821 ((null temp) ans)
1822 (setq ans (m+ ans (num-of-logs (car temp))))))
1824 (defun %e-right-placep (%e-arg)
1825 (let ((%e-arg-diff (sdiff %e-arg var)))
1826 (cond
1827 ((free %e-arg-diff var)) ;simple cases
1828 ((or (and (mexptp denom)
1829 (equal (cadr denom) -1))
1830 (polyinx (m^ denom -1) var ())) ())
1831 ((let ((%e-arg-diff-lim (ridofab (limit %e-arg-diff var val 'think)))
1832 (%e-arg-exp-lim (ridofab (limit (m^ '$%e %e-arg) var val 'think))))
1833 #+nil
1834 (progn
1835 (format t "%e-arg-dif-lim = ~A~%" %e-arg-diff-lim)
1836 (format t "%e-arg-exp-lim = ~A~%" %e-arg-exp-lim))
1837 (cond ((equal %e-arg-diff-lim %e-arg-exp-lim)
1839 ((and (mnump %e-arg-diff-lim) (mnump %e-arg-exp-lim))
1841 ((and (mnump %e-arg-diff-lim) (infinityp %e-arg-exp-lim))
1842 ;; This is meant to make maxima handle bug 1469411
1843 ;; correctly. Undoubtedly, this needs work.
1845 (t ())))))))
1847 (defun trig-right-placep (trig-type arg)
1848 (let ((arglim (ridofab (limit arg var val 'think)))
1849 (triglim (ridofab (limit `((,trig-type) ,arg) var val 'think))))
1850 (cond ((and (equal arglim 0) (equal triglim 0)) t)
1851 ((and (infinityp arglim) (infinityp triglim)) t)
1852 (t ()))))
1854 ;;Takes a numerator and a denominator. If they tries all combinations of
1855 ;;products to try and make a simpler set of subproblems for LHOSPITAL.
1856 (defun remove-singularities (numer denom)
1857 (cond ((or (null numer) (null denom)
1858 (atom numer) (atom denom)
1859 (not (mtimesp numer)) ;Leave this here for a while.
1860 (not (mtimesp denom)))
1861 (values 1 numer denom))
1863 (let ((const 1))
1864 (multiple-value-bind (num-consts num-vars)
1865 (var-or-const numer)
1866 (multiple-value-bind (denom-consts denom-vars)
1867 (var-or-const denom)
1868 (if (not (mtimesp num-vars))
1869 (setq num-vars (list num-vars))
1870 (setq num-vars (cdr num-vars)))
1871 (if (not (mtimesp denom-vars))
1872 (setq denom-vars (list denom-vars))
1873 (setq denom-vars (cdr denom-vars)))
1874 (do ((nl num-vars (cdr nl))
1875 (num-list (copy-list num-vars ))
1876 (den-list denom-vars den-list-temp)
1877 (den-list-temp (copy-list denom-vars)))
1878 ((null nl) (values (m* const (m// num-consts denom-consts))
1879 (m*l num-list)
1880 (m*l den-list-temp)))
1881 (do ((dl den-list (cdr dl)))
1882 ((null dl) t)
1883 (if (or (%einvolve (car nl)) (%einvolve (car nl)))
1885 (let ((lim (catch 'limit (simpinf (simpab (limit (m// (car nl) (car dl))
1886 var val 'think))))))
1887 (cond ((or (eq lim t)
1888 (eq lim ())
1889 (equal (ridofab lim) 0)
1890 (infinityp lim)
1891 (not (free lim '$inf))
1892 (not (free lim '$minf))
1893 (not (free lim '$infinity))
1894 (not (free lim '$ind))
1895 (not (free lim '$und)))
1898 (setq const (m* lim const))
1899 (setq num-list (delete (car nl) num-list :count 1 :test #'equal))
1900 (setq den-list-temp (delete (car dl) den-list-temp :count 1 :test #'equal))
1901 (return t)))))))))))))
1903 ;; separate terms that contain var from constant terms
1904 ;; returns (const-terms . var-terms)
1905 (defun var-or-const (expr)
1906 (setq expr ($factor expr))
1907 (cond ((atom expr)
1908 (if (eq expr var)
1909 (values 1 expr)
1910 (values expr 1)))
1911 ((free expr var)
1912 (values expr 1))
1913 ((mtimesp expr)
1914 (do ((l (cdr expr) (cdr l))
1915 (const 1)
1916 (varl 1))
1917 ((null l) (values const varl))
1918 (if (free (car l) var)
1919 (setq const (m* (car l) const))
1920 (setq varl (m* (car l) varl)))))
1922 (values 1 expr))))
1924 ;; if term goes to non-zero constant, replace with constant
1925 (defun lhsimp (term var val)
1926 (cond (($mapatom term) term)
1928 (let ((term-value (ridofab (limit term var val 'think))))
1929 (if (and (not (member term-value '($inf $minf $und $ind $infinity)))
1930 (eq t (mnqp term-value 0))) term-value term)))))
1932 (defun bylog (expo bas)
1933 (simplimexpt '$%e
1934 (setq bas
1935 (try-lhospital-quit (simplify `((%log) ,(tansc bas)))
1936 (m^ expo -1)
1937 nil))
1938 '$%e bas))
1940 (defun simplimexpt (bas expo bl el)
1941 (cond ((or (eq bl '$und) (eq el '$und)) '$und)
1942 ((zerop2 bl)
1943 (cond ((eq el '$inf) (if (eq bl '$zeroa) bl 0))
1944 ((eq el '$minf) (if (eq bl '$zeroa) '$inf '$infinity))
1945 ((eq el '$ind) '$ind)
1946 ((eq el '$infinity) '$und)
1947 ((zerop2 el) (bylog expo bas))
1948 (t (cond ((equal (getsignl el) -1)
1949 (cond ((eq bl '$zeroa) '$inf)
1950 ((eq bl '$zerob)
1951 (cond ((even1 el) '$inf)
1952 ((eq (ask-integer el '$integer) '$yes)
1953 (if (eq (ask-integer el '$even) '$yes)
1954 '$inf
1955 '$minf)))) ;Gotta be ODD.
1956 (t (setq bas (behavior bas var val))
1957 (cond ((equal bas 1) '$inf)
1958 ((equal bas -1) '$minf)
1959 (t (throw 'limit t))))))
1960 ((and (mnump el)
1961 (member bl '($zeroa $zerob) :test #'eq))
1962 (cond ((even1 el) '$zeroa)
1963 ((and (eq bl '$zerob)
1964 (ratnump el)
1965 (evenp (caddr el))) 0)
1966 (t bl)))
1967 ((equal (getsignl el) 1)
1968 (if (eq bl '$zeroa) bl 0))
1969 ((equal (getsignl el) 0)
1971 (t (throw 'limit t))))))
1972 ((eq bl '$infinity)
1973 (cond ((zerop2 el) (bylog expo bas))
1974 ((eq el '$minf) 0)
1975 ((eq el '$inf) '$infinity)
1976 ((member el '($infinity $ind) :test #'eq) '$und)
1977 ((equal (setq el (getsignl el)) 1) '$infinity)
1978 ((equal el 0) 1)
1979 ((equal el -1) 0)
1980 (t (throw 'limit t))))
1981 ((eq bl '$inf)
1982 (cond ((eq el '$inf) '$inf)
1983 ((equal el '$minf) 0)
1984 ((zerop2 el) (bylog expo bas))
1985 ((member el '($infinity $ind) :test #'eq) '$und)
1986 (t (cond ((eql 0 (getsignl el)) 1)
1987 ((ratgreaterp 0 el) '$zeroa)
1988 ((ratgreaterp el 0) '$inf)
1989 (t (throw 'limit t))))))
1990 ((eq bl '$minf)
1991 (cond ((zerop2 el) (bylog expo bas))
1992 ((eq el '$inf) '$und)
1993 ((equal el '$minf) 0)
1994 ;;;Why not generalize this. We can ask about the number. -Jim 2/23/81
1995 ((mnump el) (cond ((mnegp el)
1996 (if (even1 el)
1997 '$zeroa
1998 (if (eq (ask-integer el '$integer) '$yes)
1999 (if (eq (ask-integer el '$even) '$yes)
2000 '$zeroa
2001 '$zerob)
2002 0)))
2003 (t (cond ((even1 el) '$inf)
2004 ((eq (ask-integer el '$integer) '$yes)
2005 (if (eq (ask-integer el '$even) '$yes)
2006 '$inf
2007 '$minf))
2008 (t '$infinity)))))
2009 (loginprod? (throw 'lip? 'lip!))
2010 (t '$und)))
2011 ((equal (simplify (ratdisrep (ridofab bl))) 1)
2012 (if (infinityp el) (bylog expo bas) 1))
2013 ((and (equal (ridofab bl) -1)
2014 (infinityp el)) '$ind) ;LB
2015 ((eq bl '$ind) (cond ((or (zerop2 el) (infinityp el)) '$und)
2016 ((not (equal (getsignl el) -1)) '$ind)
2017 (t '$und)))
2018 ((eq el '$inf) (cond ((abeq1 bl)
2019 (if (equal (getsignl bl) 1) 1 '$ind))
2020 ((abless1 bl)
2021 (if (equal (getsignl bl) 1) '$zeroa 0))
2022 ((equal (getsignl (m1- bl)) 1) '$inf)
2023 ((equal (getsignl (m1- `((mabs) ,bl))) 1) '$infinity)
2024 (t (throw 'limit t))))
2025 ((eq el '$minf) (cond ((abeq1 bl)
2026 (if (equal (getsignl bl) 1) 1 '$ind))
2027 ((not (abless1 bl))
2028 (if (equal (getsignl bl) 1) '$zeroa 0))
2029 ((ratgreaterp 0 bl) '$infinity)
2030 (t '$inf)))
2031 ((eq el '$infinity)
2032 (if (equal val '$infinity)
2033 '$und ;Not enough info to do anything.
2034 (destructuring-bind (real-el . imag-el)
2035 (trisplit expo)
2036 (setq real-el (limit real-el var origval nil))
2037 (cond ((eq real-el '$minf)
2039 ((and (eq real-el '$inf)
2040 (not (equal (ridofab (limit imag-el var origval nil)) 0)))
2041 '$infinity)
2042 ((eq real-el '$infinity)
2043 (throw 'limit t)) ;; don't really know real component
2045 '$ind)))))
2047 ((eq el '$ind) '$ind)
2048 ((zerop2 el) 1)
2049 ((zerop2 el) 1)
2050 ;; When bl is off the negative real axis, use direct substitution
2051 ((off-negative-real-axisp bl) (ftake 'mexpt bl el))
2053 ;; We're looking at (neg + {zerob, 0 zeroa} %i)^el. We need to
2054 ;; do a rectform on bas and decide if the imaginary part is
2055 ;; zerob, 0, or zeroa.
2056 (let ((x) (y) (xlim) (ylim) (preserve-direction t))
2057 (setq bas (risplit bas))
2058 (setq x (car bas)
2059 y (cdr bas))
2060 (setq xlim (limit x var val 'think))
2061 (setq ylim (limit y var val 'think))
2062 (cond ((eql 0 y) (ftake 'mexpt bl el))
2063 ((eq ylim '$zeroa)
2064 (mul (ftake 'mexpt (mul -1 xlim) el)
2065 (ftake 'mexpt '$%e (mul '$%i '$%pi el))))
2066 ((eq ylim '$zerob)
2067 (mul (ftake 'mexpt (mul -1 xlim) el)
2068 (ftake 'mexpt '$%e (mul -1 '$%i '$%pi el))))
2069 (t (throw 'limit nil)))))))
2071 (defun even1 (x)
2072 (cond ((numberp x) (and (integerp x) (evenp x)))
2073 ((and (mnump x) (evenp (cadr x))))))
2075 ;; is absolute value less than one?
2076 (defun abless1 (bl)
2077 (setq bl (nmr bl))
2078 (cond ((mnump bl)
2079 (and (ratgreaterp 1. bl) (ratgreaterp bl -1.)))
2080 (t (equal (getsignl (m1- `((mabs) ,bl))) -1.))))
2082 ;; is absolute value equal to one?
2083 (defun abeq1 (bl)
2084 (setq bl (nmr bl))
2085 (cond ((mnump bl)
2086 (or (equal 1. bl) (equal bl -1.)))
2087 (t (equal (getsignl (m1- `((mabs) ,bl))) 0))))
2089 (defun simplimit (exp var val &aux op)
2090 (cond
2091 ((eq var exp) val)
2092 ((or (atom exp) (mnump exp)) exp)
2093 ;; Lookup and dispatch a simplim%function from the property list
2094 ((setq op (safe-get (mop exp) 'simplim%function))
2095 (funcall op exp var val))
2097 ;; And do the same for subscripted:
2098 ((and (consp exp) (consp (car exp)) (eq (caar exp) 'mqapply)
2099 (setq op (safe-get (subfunname exp) 'simplim%function)))
2100 (funcall op exp var val))
2102 ;; Without the call to rootscontract,
2103 ;; limit(((-4)*x^2-10*x+24)/((4*x+8)^(1/3)+2),x,-4)
2104 ;; returns zero (should be 66). This bug is due to the fact that
2105 ;; 4^(1/3)*2^(1/3)-2 does not simplify to zero. Although the call
2106 ;; to rootscontract takes care of this case, almost surely there are
2107 ;; many other limit problems that need more than rootscontract.
2108 ((mplusp exp) (let (($rootsconmode nil)) ($rootscontract (simplimplus exp))))
2109 ((mtimesp exp) (simplimtimes (cdr exp)))
2110 ((mexptp exp) (simplimexpt (cadr exp) (caddr exp)
2111 (limit (cadr exp) var val 'think)
2112 (limit (caddr exp) var val 'think)))
2113 ((member (caar exp) '(%sin %cos) :test #'eq)
2114 (simplimsc exp (caar exp) (limit (cadr exp) var val 'think)))
2115 ((eq (caar exp) '%tan) (simplim%tan (cadr exp)))
2116 ((member (caar exp) '(%sinh %cosh) :test #'eq)
2117 (simplimsch (caar exp) (limit (cadr exp) var val 'think)))
2118 ((member (caar exp) '(%erf %tanh) :test #'eq)
2119 (simplim%erf-%tanh (caar exp) (cadr exp)))
2120 ((eq (caar exp) '%atanh)
2121 (simplim%atanh (limit (cadr exp) var val 'think) val))
2122 ((eq (caar exp) '%acosh)
2123 (simplim%acosh (limit (cadr exp) var val 'think)))
2124 ((eq (caar exp) '%asinh)
2125 (simplim%asinh (limit (cadr exp) var val 'think)))
2126 ((eq (caar exp) '%inverse_jacobi_ns)
2127 (simplim%inverse_jacobi_ns (limit (cadr exp) var val 'think) (third exp)))
2128 ((eq (caar exp) '%inverse_jacobi_nc)
2129 (simplim%inverse_jacobi_nc (limit (cadr exp) var val 'think) (third exp)))
2130 ((eq (caar exp) '%inverse_jacobi_sc)
2131 (simplim%inverse_jacobi_sc (limit (cadr exp) var val 'think) (third exp)))
2132 ((eq (caar exp) '%inverse_jacobi_cs)
2133 (simplim%inverse_jacobi_cs (limit (cadr exp) var val 'think) (third exp)))
2134 ((eq (caar exp) '%inverse_jacobi_dc)
2135 (simplim%inverse_jacobi_dc (limit (cadr exp) var val 'think) (third exp)))
2136 ((eq (caar exp) '%inverse_jacobi_ds)
2137 (simplim%inverse_jacobi_ds (limit (cadr exp) var val 'think) (third exp)))
2138 ((and (eq (caar exp) 'mqapply)
2139 (eq (subfunname exp) '$psi))
2140 (simplim$psi (subfunsubs exp) (subfunargs exp) val))
2141 ((and (eq (caar exp) var)
2142 (member 'array (car exp) :test #'eq)
2143 (every #'(lambda (sub-exp)
2144 (free sub-exp var))
2145 (cdr exp)))
2146 exp) ;LIMIT(B[I],B,INF); -> B[I]
2147 ;; When limsubst is true, limit(f(n+1)/f(n),n,inf) = 1. The user documentation
2148 ;; warns against setting limsubst to true.
2149 (t (if $limsubst
2150 (simplify (cons (operator-with-array-flag exp)
2151 (mapcar #'(lambda (a)
2152 (limit a var val 'think))
2153 (cdr exp))))
2154 (throw 'limit t)))))
2156 (defun liminv (e)
2157 (setq e (resimplify (subst (m// 1 var) var e)))
2158 (let ((new-val (cond ((eq val '$zeroa) '$inf)
2159 ((eq val '$zerob) '$minf))))
2160 (if new-val (let ((preserve-direction t))
2161 (toplevel-$limit e var new-val)) (throw 'limit t))))
2163 (defun simplimtimes (exp)
2164 ;; The following test
2165 ;; handles (-1)^x * 2^x => (-2)^x => $infinity
2166 ;; wants to avoid (-1)^x * 2^x => $ind * $inf => $und
2167 (let ((try
2168 (and (expfactorp (cons '(mtimes) exp) 1)
2169 (expfactor (cons '(mtimes) exp) 1 var))))
2170 (when try (return-from simplimtimes try)))
2172 (let ((prod 1) (num 1) (denom 1)
2173 (zf nil) (ind-flag nil) (inf-type nil)
2174 (constant-zero nil) (constant-infty nil))
2175 (dolist (term exp)
2176 (let* ((loginprod? (involve term '(%log)))
2177 (y (catch 'lip? (limit term var val 'think))))
2178 (cond
2179 ;; limit failed due to log in product
2180 ((eq y 'lip!)
2181 (return-from simplimtimes (liminv (cons '(mtimes simp) exp))))
2183 ;; If the limit is infinitesimal or zero
2184 ((zerop2 y)
2185 (setf num (m* num term)
2186 constant-zero (or constant-zero (not (among var term))))
2187 (case y
2188 ($zeroa
2189 (unless zf (setf zf 1)))
2190 ($zerob
2191 (setf zf (* -1 (or zf 1))))))
2193 ;; If the limit is not some form of infinity or
2194 ;; undefined/indeterminate.
2195 ((not (member y '($inf $minf $infinity $ind $und) :test #'eq))
2196 (setq prod (m* prod y)))
2198 ((eq y '$und) (return-from simplimtimes '$und))
2199 ((eq y '$ind) (setq ind-flag t))
2201 ;; Some form of infinity
2203 (setf denom (m* denom term)
2204 constant-infty (or constant-infty (not (among var term))))
2205 (unless (eq inf-type '$infinity)
2206 (cond
2207 ((eq y '$infinity) (setq inf-type '$infinity))
2208 ((null inf-type) (setf inf-type y))
2209 ;; minf * minf or inf * inf
2210 ((eq y inf-type) (setf inf-type '$inf))
2211 ;; minf * inf
2212 (t (setf inf-type '$minf))))))))
2214 (cond
2215 ;; If there are zeros and infinities among the terms that are free of
2216 ;; VAR, then we have an expression like "inf * zeroa * f(x)" or
2217 ;; similar. That gives an undefined result. Note that we don't
2218 ;; necessarily have something undefined if only the zeros have a term
2219 ;; free of VAR. For example "zeroa * exp(-1/x) * 1/x" as x -> 0. And
2220 ;; similarly for the infinities.
2221 ((and constant-zero constant-infty) '$und)
2223 ;; If num=denom=1, we didn't find any explicit infinities or zeros, so we
2224 ;; either return the simplified product or ind
2225 ((and (eql num 1) (eql denom 1))
2226 (if ind-flag '$ind prod))
2227 ;; If denom=1 (and so num != 1), we have some form of zero
2228 ((equal denom 1)
2229 (if (null zf)
2231 (let ((sign (getsignl prod)))
2232 (if (or (not sign) (eq sign 'complex))
2234 (ecase (* zf sign)
2235 (0 0)
2236 (1 '$zeroa)
2237 (-1 '$zerob))))))
2238 ;; If num=1 (and so denom != 1), we have some form of infinity
2239 ((equal num 1)
2240 (let ((sign ($csign prod)))
2241 (cond
2242 (ind-flag '$und)
2243 ((eq sign '$pos) inf-type)
2244 ((eq sign '$neg) (case inf-type
2245 ($inf '$minf)
2246 ($minf '$inf)
2247 (t '$infinity)))
2248 ((member sign '($complex $imaginary)) '$infinity)
2249 ; sign is '$zero, $pnz, $pz, etc
2250 (t (throw 'limit t)))))
2251 ;; Both zeros and infinities
2253 ;; All bets off if there are some infinities or some zeros, but it
2254 ;; needn't be undefined (see above)
2255 (when (or constant-zero constant-infty) (throw 'limit t))
2257 (let ((ans (limit2 num (m^ denom -1) var val)))
2258 (if ans
2259 (simplimtimes (list prod ans))
2260 (throw 'limit t)))))))
2262 ;;;PUT CODE HERE TO ELIMINATE FAKE SINGULARITIES??
2264 ;; At one time when simplimplus1 failed to find a limit, this function
2265 ;; applied ratsimp and tried again. This scheme didn't fix any testsuite
2266 ;; bugs and it slowed the code, so I removed it (Barton Willis, July 2023).
2267 (defun simplimplus (exp)
2268 (cond ((memalike exp simplimplus-problems) (throw 'limit t))
2269 (t (unwind-protect
2270 (progn (push exp simplimplus-problems)
2271 (let ((ans (catch 'limit (simplimplus1 exp))))
2272 (if (or (eq ans nil) (eq ans t) (among '%limit ans))
2273 (throw 'limit t) (resimp-extra-simp ans))))
2274 (pop simplimplus-problems)))))
2276 (defun simplimplus1 (exp)
2277 (prog (sum y infl infinityl minfl indl undl zerobl zeroal ans r)
2278 (do ((exp (cdr exp) (cdr exp)) (f))
2279 ((null exp) nil)
2280 (setq f (limit (car exp) var val 'think))
2281 (cond ((null f) (throw 'limit t))
2282 ((eq f '$und) (push (car exp) undl))
2283 ((eq f '$zerob) (push (car exp) zerobl))
2284 ((eq f '$zeroa) (push (car exp) zeroal))
2285 ((eq f '$ind) (push (car exp) indl))
2286 ((eq f '$inf) (push (car exp) infl))
2287 ((eq f '$minf) (push (car exp) minfl))
2288 ((eq f '$infinity) (push (car exp) infinityl))
2289 (t (push f sum))))
2291 ;; When there are two or more infinity terms, we dispatch gruntz1 on
2292 ;; the rectangular form of their sum. When gruntz1 is able to find the
2293 ;; limit, we modify the lists infinityl, minfl, ... accordingly.
2294 (when (and infinityl (cdr infinityl) (not (among '$li (cons '(mlist) infinityl))))
2295 (setq ans (risplit (fapply 'mplus infinityl)))
2297 (let ((re (car ans)) (im (cdr ans)))
2298 (setq re (car (errcatch (gruntz1 re var val))))
2299 (setq im (car (errcatch (gruntz1 im var val))))
2300 (setq r
2301 (cond ((or (null re) (null im)) nil)
2302 ((infinityp im) '$infinity)
2303 ((infinityp re) re)
2304 (t (add re (mul '$%i im))))))
2305 (cond ((eq r '$infinity) (list (fapply 'mplus infinityl)))
2306 ((eq r nil) (throw 'limit t))
2308 (setq infinityl nil)
2309 (cond ((eq r '$zerob) (push ans zerobl))
2310 ((eq r '$zeroa) (push ans zeroal))
2311 ((eq r '$ind) (push ans indl))
2312 ((eq r '$und) (push ans undl))
2313 ((eq r '$minf) (push ans minfl))
2314 ((eq r '$inf) (push ans infl))
2315 (t (push r sum))))))
2317 ;; Unfortunately, this code does not handle the case of one or more
2318 ;; infinity terms and either a minf or inf term. So we throw an error.
2319 (when (and infinityl (or minfl infl))
2320 (throw 'limit t))
2322 ;; Blend the zerob, zeroa, and sum terms. When there are both zerob
2323 ;; and zeroa terms, ignore them. When preserve-direction is true and
2324 ;; there are zerob terms, push zerob into the sum terms. And do the same
2325 ;; for zeroa. After that, add the terms in the list sum.
2326 (when (and preserve-direction zerobl (null zeroal))
2327 (push '$zerob sum))
2328 (when (and preserve-direction zeroal (null zerobl))
2329 (push '$zeroa sum))
2331 ;; When indl has two or more members, we attempt to condense the
2332 ;; ind terms into a single term.
2333 (when (and indl (cdr indl))
2334 ;; Use factor to attempt to condense the ind terms
2335 ;; into a finite term. This is needed for cases such as
2336 ;; limit(cos(1/x)*sin(x)-sin(x),x,inf). When there is only
2337 ;; one ind term, set ans to ind.
2338 (setq ans ($factor (fapply 'mplus indl)))
2339 (setq r (if (mplusp ans) nil (limit ans var val 'think)))
2340 (cond ((eq r '$zerob)
2341 (push ans zerobl)
2342 (setq indl nil))
2343 ((eq r '$zeroa)
2344 (push ans zeroal)
2345 (setq indl nil))
2346 ((eq r '$ind) (setq indl (list ans)))
2347 ((eq r '$und)
2348 (setq indl nil)
2349 (push ans undl))
2350 ((or (eq r '$minf) (eq r '$inf) (eq r '$infinity))
2351 (throw 'limit t))
2352 ((eq r nil))
2353 (t (push r sum))))
2354 ;; Add the members of the list sum.
2355 (setq sum (fapply 'mplus sum))
2357 (cond (undl
2358 (if (or infl minfl indl infinityl)
2359 (setq infinityl (append undl infinityl)); x^2 + x*sin(x)
2360 (return '$und))) ; 1 + x*sin(x)
2361 ((not (or infl minfl indl infinityl))
2362 (return (cond ((atom sum) sum)
2363 ((or (not (free sum '$zeroa))
2364 (not (free sum '$zerob)))
2365 (simpab sum))
2366 (t sum))))
2367 (t (cond ((null infinityl)
2368 (cond (infl (cond ((null minfl) (return '$inf))
2369 (t (go oon))))
2370 (minfl (return '$minf))
2371 (indl (return '$ind))))
2372 (t (setq infl (append infl infinityl))))))
2374 oon (setq y (m+l (append minfl infl)))
2375 (cond ((alike1 exp (setq y (sratsimp (hyperex y))))
2376 (cond ((not (infinityp val))
2377 (setq infl (cnv infl val)) ;THIS IS HORRIBLE!!!!
2378 (setq minfl (cnv minfl val))))
2379 (let ((val '$inf))
2380 (cond ((every #'(lambda (j) (radicalp j var))
2381 (append infl minfl))
2382 (setq y (rheur infl minfl)))
2383 (t (setq y (sheur infl minfl))))))
2384 (t (setq y (limit y var val 'think))))
2385 (cond ((or (eq y ())
2386 (eq y t)) (return ()))
2387 ((infinityp y) (return y))
2388 (indl (return '$ind))
2389 (t (return (m+ sum y))))))
2391 ;; Limit n/d, using heuristics on the order of growth.
2392 (defun sheur0 (n d)
2393 (let ((orig-n n))
2394 (cond ((and (free n var)
2395 (free d var))
2396 (m// n d))
2397 (t (setq n (cpa n d nil))
2398 (cond ((equal n 1)
2399 (cond ((oscip orig-n) '$und)
2400 (t '$inf)))
2401 ((equal n -1) '$zeroa)
2402 ((equal n 0) (m// orig-n d)))))))
2405 ;;;L1 is a list of INF's and L2 is a list of MINF's. Added together
2406 ;;;it is indeterminate.
2407 (defun sheur (l1 l2)
2408 (let ((term (sheur1 l1 l2)))
2409 (cond ((equal term '$inf) '$inf)
2410 ((equal term '$minf) '$minf)
2411 (t (let ((new-num (m+l (mapcar #'(lambda (num-term)
2412 (m// num-term (car l1)))
2413 (append l1 l2)))))
2414 (cond ((limit2 new-num (m// 1 (car l1)) var val))))))))
2416 (defun frac (exp)
2417 (cond ((atom exp) nil)
2418 (t (setq exp (nformat exp))
2419 (cond ((and (eq (caar exp) 'mquotient)
2420 (among var (caddr exp)))
2421 t)))))
2423 (defun zerop2 (z) (=0 (ridofab z)))
2425 (defun raise (a) (m+ a '$zeroa))
2427 (defun lower (a) (m+ a '$zerob))
2429 (defun sincoshk (exp1 l sc)
2430 (cond ((equal l 1) (lower l))
2431 ((equal l -1) (raise l))
2432 ((among sc l) l)
2433 ((member val '($zeroa $zerob) :test #'eq) (spangside exp1 l))
2434 (t l)))
2436 (defun spangside (e l)
2437 (setq e (behavior e var val))
2438 (cond ((equal e 1) (raise l))
2439 ((equal e -1) (lower l))
2440 (t l)))
2442 ;; get rid of zeroa and zerob
2443 (defun ridofab (e)
2444 (if (among '$zeroa e) (setq e (maxima-substitute 0 '$zeroa e)))
2445 (if (among '$zerob e) (setq e (maxima-substitute 0 '$zerob e)))
2448 ;; simple radical
2449 ;; returns true if exp is a polynomial raised to a numeric power
2450 (defun simplerd (exp)
2451 (and (mexptp exp)
2452 (mnump (caddr exp)) ;; exponent must be a number - no variables
2453 (polyp (cadr exp))))
2455 (defun branch1 (exp val)
2456 (cond ((polyp exp) nil)
2457 ((simplerd exp) (zerop2 (subin val (cadr exp))))
2459 (loop for v on (cdr exp)
2460 when (branch1 (car v) val)
2461 do (return v)))))
2463 (defun branch (exp val)
2464 (cond ((polyp exp) nil)
2465 ((or (simplerd exp) (mtimesp exp))
2466 (branch1 exp val))
2467 ((mplusp exp)
2468 (every #'(lambda (j) (branch j val)) (the list (cdr exp))))))
2470 (defun ser0 (e n d val)
2471 (cond ((and (branch n val) (branch d val))
2472 (setq nn* nil)
2473 (setq n (ser1 n))
2474 (setq d (ser1 d))
2475 ;;;NN* gets set by POFX, called by SER1, to get a list of exponents.
2476 (setq nn* (ratmin nn*))
2477 (setq n (sratsimp (m^ n (m^ var nn*))))
2478 (setq d (sratsimp (m^ d (m^ var nn*))))
2479 (cond ((member val '($zeroa $zerob) :test #'eq) nil)
2480 (t (setq val 0.)))
2481 (radlim e n d))
2482 (t (try-lhospital-quit n d nil))))
2484 (defun rheur (l1 l2)
2485 (prog (ans m1 m2)
2486 (setq m1 (mapcar (function asymredu) l1))
2487 (setq m2 (mapcar (function asymredu) l2))
2488 (setq ans (m+l (append m1 m2)))
2489 (cond ((rptrouble (m+l (append l1 l2)))
2490 (return (limit (simplify (rdsget (m+l (append l1 l2))))
2493 nil)))
2494 ((mplusp ans) (return (sheur m1 m2)))
2495 (t (return (limit ans var val t))))))
2497 (defun rptrouble (rp)
2498 (not (equal (rddeg rp nil) (rddeg (asymredu rp) nil))))
2500 (defun radicalp (exp var)
2501 (cond ((polyinx exp var ()))
2502 ((mexptp exp) (cond ((equal (caddr exp) -1.)
2503 (radicalp (cadr exp) var))
2504 ((simplerd exp))))
2505 ((member (caar exp) '(mplus mtimes) :test #'eq)
2506 (every #'(lambda (j) (radicalp j var))
2507 (cdr exp)))))
2509 (defun involve (e nn*)
2510 (declare (special var))
2511 (cond ((atom e) nil)
2512 ((mnump e) nil)
2513 ((and (member (caar e) nn* :test #'eq) (among var (cdr e))) (cadr e))
2514 (t (some #'(lambda (j) (involve j nn*)) (cdr e)))))
2516 ;; Just like INVOLVE, except the dependency on VAR is explicit (second
2517 ;; arg here). Use this instead.
2518 (defun involve-var (e var1 nn*)
2519 (cond ((atom e) nil)
2520 ((mnump e) nil)
2521 ((and (member (caar e) nn* :test #'eq)
2522 (among var1 (cdr e)))
2523 (cadr e))
2525 (some #'(lambda (j)
2526 (involve-var j var1 nn*))
2527 (cdr e)))))
2529 ;; Why not implement this as (NOT (INVOLVE EXP NN*))?
2530 (defun notinvolve (exp nn*)
2531 (cond ((atom exp) t)
2532 ((mnump exp) t)
2533 ((member (caar exp) nn* :test #'eq) (not (among var (cdr exp))))
2534 ((every #'(lambda (j) (notinvolve j nn*))
2535 (cdr exp)))))
2537 ;; Just like NOTINVOLVE, except the dependency on VAR is explicit
2538 ;; (second arg here). Use this instead.
2539 (Defun notinvolve-var (exp var1 nn*)
2540 (cond ((atom exp)
2542 ((mnump exp)
2544 ((member (caar exp) nn* :test #'eq)
2545 (not (among var1 (cdr exp))))
2546 ((every #'(lambda (j)
2547 (notinvolve-var j var1 nn*))
2548 (cdr exp)))))
2550 (defun sheur1 (l1 l2)
2551 (prog (ans)
2552 (setq l1 (mapcar #'stirling0 l1))
2553 (setq l2 (mapcar #'stirling0 l2))
2554 (setq l1 (m+l (maxi l1)))
2555 (setq l2 (m+l (maxi l2)))
2556 (setq ans (cpa l1 l2 t))
2557 (return (cond ((=0 ans) (m+ l1 l2))
2558 ((equal ans 1.) '$inf)
2559 (t '$minf)))))
2561 (defun zero-lim (cpa-list)
2562 (do ((l cpa-list (cdr l)))
2563 ((null l) ())
2564 (and (eq (caar l) 'gen)
2565 (zerop2 (limit (cadar l) var val 'think))
2566 (return t))))
2568 ;; Compare order of growth for R1 and R2. The result is 0, -1, +1
2569 ;; depending on the relative order of growth. 0 is returned if R1 and
2570 ;; R2 have the same growth; -1 if R1 grows much more slowly than R2;
2571 ;; +1 if R1 grows much more quickly than R2.
2572 (defun cpa (r1 r2 flag)
2573 (let ((t1 r1)
2574 (t2 r2))
2575 (cond ((alike1 t1 t2) 0.)
2576 ((free t1 var)
2577 (cond ((free t2 var) 0.)
2578 (t (let ((lim-ans (limit1 t2 var val)))
2579 (cond ((not (member lim-ans '($inf $minf $und $ind) :test #'eq)) 0.)
2580 (t -1.))))))
2581 ((free t2 var)
2582 (let ((lim-ans (limit1 t1 var val)))
2583 (cond ((not (member lim-ans '($inf $minf $und $ind) :test #'eq)) 0.)
2584 (t 1.))))
2586 ;; Make T1 and T2 be a list of terms that are multiplied
2587 ;; together.
2588 (cond ((mtimesp t1) (setq t1 (cdr t1)))
2589 (t (setq t1 (list t1))))
2590 (cond ((mtimesp t2) (setq t2 (cdr t2)))
2591 (t (setq t2 (list t2))))
2592 ;; Find the strengths of each term of T1 and T2
2593 (setq t1 (mapcar (function istrength) t1))
2594 (setq t2 (mapcar (function istrength) t2))
2595 ;; Compute the max of the strengths of the terms.
2596 (let ((ans (ismax t1))
2597 (d (ismax t2)))
2598 (cond ((or (null ans) (null d))
2599 ;;(eq (car ans) 'gen) (eq (car d) 'gen))
2600 ;; ismax couldn't find highest term; give up
2603 (if (eq (car ans) 'var) (setq ans (add-up-deg t1)))
2604 (if (eq (car d) 'var) (setq d (add-up-deg t2)))
2605 ;; Can't just just compare dominating terms if there are
2606 ;; indeterm-inates present; e.g. X-X^2*LOG(1+1/X). So
2607 ;; check for this.
2608 (cond ((or (zero-lim t1)
2609 (zero-lim t2))
2610 (cpa-indeterm ans d t1 t2 flag))
2611 ((isgreaterp ans d) 1.)
2612 ((isgreaterp d ans) -1.)
2613 (t 0)))))))))
2615 (defun cpa-indeterm (ans d t1 t2 flag)
2616 (cond ((not (eq (car ans) 'var))
2617 (setq ans (gather ans t1) d (gather d t2))))
2618 (let ((*indicator (and (eq (car ans) 'exp)
2619 flag))
2620 (test ()))
2621 (setq test (cpa1 ans d))
2622 (cond ((and (zerop1 test)
2623 (or (equal ($radcan (m// (cadr ans) (cadr d))) 1.)
2624 (and (polyp (cadr ans))
2625 (polyp (cadr d))
2626 (equal (limit (m// (cadr ans) (cadr d)) var val 'think)
2627 1.))))
2628 (let ((new-term1 (m// t1 (cadr ans)))
2629 (new-term2 (m// t2 (cadr d))))
2630 (cpa new-term1 new-term2 flag)))
2631 (t 0))))
2633 (defun add-up-deg (strengthl)
2634 (do ((stl strengthl (cdr stl))
2635 (poxl)
2636 (degl))
2637 ((null stl) (list 'var (m*l poxl) (m+l degl)))
2638 (cond ((eq (caar stl) 'var)
2639 (push (cadar stl) poxl)
2640 (push (caddar stl) degl)))))
2642 (defun cpa1 (p1 p2)
2643 (prog (flag s1 s2)
2644 (cond ((eq (car p1) 'gen) (return 0.)))
2645 (setq flag (car p1))
2646 (setq p1 (cadr p1))
2647 (setq p2 (cadr p2))
2648 (cond
2649 ((eq flag 'var)
2650 (setq s1 (istrength p1))
2651 (setq s2 (istrength p2))
2652 (return
2653 (cond
2654 ((isgreaterp s1 s2) 1.)
2655 ((isgreaterp s2 s1) -1.)
2656 (*indicator
2657 (setq *indicator nil)
2658 (cond
2659 ((and (poly? p1 var) (poly? p2 var))
2660 (setq p1 (m- p1 p2))
2661 (cond ((zerop1 p1) 0.)
2662 (t (getsignl (hot-coef p1)))))
2664 (setq s1
2665 (rheur (list p1)
2666 (list (m*t -1 p2))))
2667 (cond ((zerop2 s1) 0.)
2668 ((ratgreaterp s1 0.) 1.)
2669 (t -1.)))))
2670 (t 0.))))
2671 ((eq flag 'exp)
2672 (setq p1 (caddr p1))
2673 (setq p2 (caddr p2))
2674 (cond ((and (poly? p1 var) (poly? p2 var))
2675 (setq p1 (m- p1 p2))
2676 (return (cond ((or (zerop1 p1)
2677 (not (among var p1)))
2679 (t (getsignl (hot-coef p1))))))
2680 ((and (radicalp p1 var) (radicalp p2 var))
2681 (setq s1
2682 (rheur (list p1)
2683 (list (m*t -1 p2))))
2684 (return (cond ((eq s1 '$inf) 1.)
2685 ((eq s1 '$minf) -1.)
2686 ((mnump s1)
2687 (cond ((ratgreaterp s1 0.) 1.)
2688 ((ratgreaterp 0. s1) -1.)
2689 (t 0.)))
2690 (t 0.))))
2691 (t (return (cpa p1 p2 t)))))
2692 ((eq flag 'log)
2693 (setq p1 (try-lhospital (asymredu p1) (asymredu p2) nil))
2694 (return (cond ((zerop2 p1) -1.)
2695 ((real-infinityp p1) 1.)
2696 (t 0.)))))))
2698 ;;;EXPRESSIONS TO ISGREATERP ARE OF THE FOLLOWING FORMS
2699 ;;; ("VAR" POLY DEG)
2700 ;;; ("EXP" %E^EXP)
2701 ;;; ("LOG" LOG(EXP))
2702 ;;; ("FACT" <A FACTORIAL EXPRESSION>)
2703 ;;; ("GEN" <ANY OTHER TYPE OF EXPRESSION>)
2705 (defun isgreaterp (a b)
2706 (let ((ta (car a))
2707 (tb (car b)))
2708 (cond ((or (eq ta 'gen)
2709 (eq tb 'gen)) ())
2710 ((and (eq ta tb) (eq ta 'var))
2711 (ratgreaterp (caddr a) (caddr b)))
2712 ((and (eq ta tb) (eq ta 'exp))
2713 ;; Both are exponential order of infinity. Check the
2714 ;; exponents to determine which exponent is bigger.
2715 (eq (limit (m- `((%log) ,(second a)) `((%log) ,(second b)))
2716 var val 'think)
2717 '$inf))
2718 ((member ta (cdr (member tb '(num log var exp fact gen) :test #'eq)) :test #'eq)))))
2720 (defun ismax (l)
2721 ;; Preprocess the list of products. Separate the terms that
2722 ;; exponentials and those that don't. Actually multiply the
2723 ;; exponential terms together to form a single term. Pass this and
2724 ;; the rest to ismax-core to find the max.
2725 (let (exp-terms non-exp-terms)
2726 (dolist (term l)
2727 (if (eq 'exp (car term))
2728 (push term exp-terms)
2729 (push term non-exp-terms)))
2730 ;; Multiply the exp-terms together
2731 (if exp-terms
2732 (let ((product 1))
2733 ;;(format t "exp-terms = ~A~%" exp-terms)
2734 (dolist (term exp-terms)
2735 (setf product (simplify (mul product (second term)))))
2736 ;;(format t "product = ~A~%" product)
2737 (setf product `(exp ,($logcontract product)))
2738 ;;(format t "product = ~A~%" product)
2739 (ismax-core (cons product non-exp-terms)))
2740 (ismax-core l))))
2742 (defun ismax-core (l)
2743 (cond ((null l) ())
2744 ((atom l) ())
2745 ((= (length l) 1) (car l)) ;If there is only 1 thing give it back.
2746 ((every #'(lambda (x)
2747 (not (eq (car x) 'gen))) l)
2749 (do ((l1 (cdr l) (cdr l1))
2750 (temp-ans (car l))
2751 (ans ()))
2752 ((null l1) ans)
2753 (cond ((isgreaterp temp-ans (car l1))
2754 (setq ans temp-ans))
2755 ((isgreaterp (car l1) temp-ans)
2756 (setq temp-ans (car l1))
2757 (setq ans temp-ans))
2758 (t (setq ans ())))))
2759 (t ())))
2761 ;RETURNS LIST OF HIGH TERMS
2762 (defun maxi (all)
2763 (cond ((atom all) nil)
2764 (t (do ((l (cdr all) (cdr l))
2765 (hi-term (car all))
2766 (total 1) ; running total constant factor of hi-term
2767 (hi-terms (ncons (car all)))
2768 (compare nil))
2769 ((null l) (if (zerop2 total) ; if high-order terms cancel each other
2770 all ; keep everything
2771 hi-terms)) ; otherwise return list of high terms
2772 (setq compare (limit (m// (car l) hi-term) var val 'think))
2773 (cond
2774 ((or (infinityp compare)
2775 (and (eq compare '$und)
2776 (zerop2 (limit (m// hi-term (car l)) var val 'think))))
2777 (setq total 1) ; have found new high term
2778 (setq hi-terms (ncons (setq hi-term (car l)))))
2779 ((zerop2 compare) nil)
2780 ;; COMPARE IS IND, FINITE-VALUED, or und in both directions
2781 (t ; add to list of high terms
2782 (setq total (m+ total compare))
2783 (setq hi-terms (append hi-terms (ncons (car l))))))))))
2785 (defun ratmax (l)
2786 (prog (ans)
2787 (cond ((atom l) (return nil)))
2788 l1 (setq ans (car l))
2789 l2 (setq l (cdr l))
2790 (cond ((null l) (return ans))
2791 ((ratgreaterp ans (car l)) (go l2))
2792 (t (go l1)))))
2794 (defun ratmin (l)
2795 (prog (ans)
2796 (cond ((atom l) (return nil)))
2797 l1 (setq ans (car l))
2798 l2 (setq l (cdr l))
2799 (cond ((null l) (return ans))
2800 ((ratgreaterp (car l) ans) (go l2))
2801 (t (go l1)))))
2803 (defun pofx (e)
2804 (cond ((atom e)
2805 (cond ((eq e var)
2806 (push 1 nn*))
2807 (t ())))
2808 ((or (mnump e) (not (among var e))) nil)
2809 ((and (mexptp e) (eq (cadr e) var))
2810 (push (caddr e) nn*))
2811 ((simplerd e) nil)
2812 (t (mapc #'pofx (cdr e)))))
2814 (defun ser1 (e)
2815 (cond ((member val '($zeroa $zerob) :test #'eq) nil)
2816 (t (setq e (subin (m+ var val) e))))
2817 (setq e (rdfact e))
2818 (cond ((pofx e) e)))
2820 (defun gather (ind l)
2821 (prog (ans)
2822 (setq ind (car ind))
2823 loop (cond ((null l)
2824 (return (list ind (m*l ans))))
2825 ((equal (caar l) ind)
2826 (push (cadar l) ans)))
2827 (setq l (cdr l))
2828 (go loop)))
2830 ; returns rough class-of-growth of term
2831 (defun istrength (term)
2832 (cond ((mnump term) (list 'num term))
2833 ((atom term) (cond ((eq term var)
2834 (list 'var var 1.))
2835 (t (list 'num term))))
2836 ((not (among var term)) (list 'num term))
2837 ((mplusp term)
2838 (let ((temp (ismax-core (mapcar #'istrength (cdr term)))))
2839 (cond ((not (null temp)) temp)
2840 (t `(gen ,term)))))
2841 ((mtimesp term)
2842 (let ((temp (mapcar #'istrength (cdr term)))
2843 (temp1 ()))
2844 (setq temp1 (ismax temp))
2845 (cond ((null temp1) `(gen ,term))
2846 ((eq (car temp1) 'log) `(log ,temp))
2847 ((eq (car temp1) 'var) (add-up-deg temp))
2848 (t `(gen ,temp)))))
2849 ((and (mexptp term)
2850 (real-infinityp (limit term var val t)))
2851 (let ((logterm (logred term)))
2852 (cond ((and (among var (caddr term))
2853 (member (car (istrength logterm))
2854 '(var exp fact) :test #'eq)
2855 (real-infinityp (limit logterm var val t)))
2856 (list 'exp (m^ '$%e logterm)))
2857 ((not (among var (caddr term)))
2858 (let ((temp (istrength (cadr term))))
2859 (cond ((not (alike1 temp term))
2860 (rplaca (cdr temp) term)
2861 (and (eq (car temp) 'var)
2862 (rplaca (cddr temp)
2863 (m* (caddr temp) (caddr term))))
2864 temp)
2865 (t `(gen ,term)))))
2866 (t `(gen ,term)))))
2867 ((and (eq (caar term) '%log)
2868 (real-infinityp (limit term var val t)))
2869 (let ((stren (istrength (cadr term))))
2870 (cond ((member (car stren) '(log var) :test #'eq)
2871 `(log ,term))
2872 ((and (eq (car stren) 'exp)
2873 (eq (caar (second stren)) 'mexpt))
2874 (istrength (logred (second stren))))
2875 (t `(gen ,term)))))
2876 ((eq (caar term) 'mfactorial)
2877 (list 'fact term))
2878 ((let ((temp (hyperex term)))
2879 (and (not (alike1 term temp))
2880 (istrength temp))))
2881 (t (list 'gen term))))
2883 ;; log reduce - returns log of s1
2884 ;; When s1 is not of the form a^b, this code doesn't return log(s1).
2885 ;; Running the testsuite does send non exptp expressions to this function.
2886 (defun logred (s1)
2887 (or (and (eq (cadr s1) '$%e) (caddr s1))
2888 (m* (caddr s1) `((%log) ,(cadr s1)))))
2890 (defun asymredu (rd)
2891 (cond ((atom rd) rd)
2892 ((mnump rd) rd)
2893 ((not (among var rd)) rd)
2894 ((polyinx rd var t))
2895 ((simplerd rd)
2896 (cond ((eq (cadr rd) var) rd)
2897 (t (mabs-subst
2898 (factor ($expand (m^ (polyinx (cadr rd) var t)
2899 (caddr rd))))
2901 val))))
2902 (t (simplify (cons (list (caar rd))
2903 (mapcar #'asymredu (cdr rd)))))))
2905 (defun rdfact (rd)
2906 (let ((dn** ()) (nn** ()))
2907 (cond ((atom rd) rd)
2908 ((mnump rd) rd)
2909 ((not (among var rd)) rd)
2910 ((polyp rd)
2911 (factor rd))
2912 ((simplerd rd)
2913 (cond ((eq (cadr rd) var) rd)
2914 (t (setq dn** (caddr rd))
2915 (setq nn** (factor (cadr rd)))
2916 (cond ((mtimesp nn**)
2917 (m*l (mapcar #'(lambda (j) (m^ j dn**))
2918 (cdr nn**))))
2919 (t rd)))))
2920 (t (simplify (cons (ncons (caar rd))
2921 (mapcar #'rdfact (cdr rd))))))))
2923 (defun cnv (expl val)
2924 (mapcar #'(lambda (e)
2925 (maxima-substitute (cond ((eq val '$zerob)
2926 (m* -1 (m^ var -1)))
2927 ((eq val '$zeroa)
2928 (m^ var -1))
2929 ((eq val '$minf)
2930 (m* -1 var))
2931 (t (m^ (m+ var (m* -1 val)) -1.)))
2934 expl))
2936 ;; We could replace pwtaylor with a call to (tlimit-taylor exp var l terms).
2937 ;; Other than eliminating clutter, I know of no advantages to doing so.
2938 (defun pwtaylor (exp var l terms)
2939 (prog (coef ans c mc)
2940 (cond ((=0 terms) (return nil)) ((=0 l) (setq mc t)))
2941 (setq c 0.)
2942 (go tag1)
2943 loop (setq c (1+ c))
2944 (cond ((or (> c 10.) (equal c terms))
2945 (return (m+l ans)))
2946 (t (setq exp (sdiff exp var))))
2947 tag1 (setq coef ($radcan (subin l exp)))
2948 (cond ((=0 coef) (setq terms (1+ terms)) (go loop)))
2949 (setq
2951 (append
2953 (list
2954 (m* coef
2955 (m^ `((mfactorial) ,c) -1)
2956 (m^ (if mc var (m+t (m*t -1 l) var)) c)))))
2957 (go loop)))
2959 (defun rdsget (e)
2960 (cond ((polyp e) e)
2961 ((simplerd e) (rdtay e))
2962 (t (cons (list (caar e))
2963 (mapcar #'rdsget (cdr e))))))
2965 (defun rdtay (rd)
2966 (cond (limit-using-taylor ($ratdisrep ($taylor rd var val 1.)))
2967 (t (lrdtay rd))))
2969 (defun lrdtay (rd)
2970 (prog (varlist p c e d $ratfac)
2971 (setq varlist (ncons var))
2972 (setq p (ratnumerator (cdr (ratrep* (cadr rd)))))
2973 (cond ((< (length p) 3.) (return rd)))
2974 (setq e (caddr rd))
2975 (setq d (pdegr p))
2976 (setq c (m^ var (m* d e)))
2977 (setq d ($ratsimp (varinvert (m* (pdis p) (m^ var (m- d)))
2978 var)))
2979 (setq d (pwtaylor (m^ d e) var 0. 3.))
2980 (return (m* c (varinvert d var)))))
2982 (defun varinvert (e var) (subin (m^t var -1.) e))
2984 (defun deg (p)
2985 (prog ((varlist (list var)))
2986 (return (let (($ratfac nil))
2987 (newvar p)
2988 (pdegr (cadr (ratrep* p)))))))
2990 ;; Like DEG, but dependency on VAR is explicit. Use this instead when
2991 ;; possible.
2992 (defun deg-var (p var1)
2993 (prog ((varlist (list var1)))
2994 (flet ((pdegr-var (pf)
2995 (cond ((or (atom pf)
2996 (not (eq (caadr (ratf var1))
2997 (car pf))))
2999 (low*
3000 (cadr (reverse pf)))
3002 (cadr pf)))))
3003 (return (let (($ratfac nil))
3004 (newvar p)
3005 (pdegr-var (cadr (ratrep* p))))))))
3007 (defun rat-no-ratfac (e)
3008 (let (($ratfac nil))
3009 (newvar e)
3010 (ratrep* e)))
3011 (setq low* nil)
3013 (defun rddeg (rd low*)
3014 (cond ((or (mnump rd)
3015 (not (among var rd)))
3017 ((polyp rd)
3018 (deg rd))
3019 ((simplerd rd)
3020 (m* (deg (cadr rd)) (caddr rd)))
3021 ((mtimesp rd)
3022 (addn (mapcar #'(lambda (j)
3023 (rddeg j low*))
3024 (cdr rd)) nil))
3025 ((and (mplusp rd)
3026 (setq rd (andmapcar #'(lambda (j) (rddeg j low*))
3027 (cdr rd))))
3028 (cond (low* (ratmin rd))
3029 (t (ratmax rd))))))
3031 (defun pdegr (pf)
3032 (cond ((or (atom pf) (not (eq (caadr (ratf var)) (car pf))))
3034 (low* (cadr (reverse pf)))
3035 (t (cadr pf))))
3036 ;;There is some confusion here. We need to be aware of Branch cuts etc....
3037 ;;when doing this section of code. It is not very carefully done so there
3038 ;;are bugs still lurking. Another misfortune is that LIMIT or its inferiors
3039 ;;sometimes decides to change the limit VAL in midstream. This must be corrected
3040 ;;since LIMIT's interaction with the data base environment must be maintained.
3041 ;;I'm not sure that this code can ever be called with VAL other than $INF but
3042 ;;there is a hook in the first important cond clause to cathc them anyway.
3044 (defun asy (n d)
3045 (let ((num-power (rddeg n nil))
3046 (den-power (rddeg d nil))
3047 (coef ()) (coef-sign ()) (power ()))
3048 (setq coef (m// ($ratcoef ($expand n) var num-power)
3049 ($ratcoef ($expand d) var den-power)))
3050 (setq coef-sign (getsignl coef))
3051 (setq power (m// num-power den-power))
3052 (cond ((eq (ask-integer power '$integer) '$integer)
3053 (cond ((eq (ask-integer power '$even) '$even) '$even)
3054 (t '$odd)))) ;Can be extended from here.
3055 (cond ((or (eq val '$minf)
3056 (eq val '$zerob)
3057 (eq val '$zeroa)
3058 (equal val 0)) ()) ;Can be extended to cover some these.
3059 ((ratgreaterp den-power num-power)
3060 (cond ((equal coef-sign 1.) '$zeroa)
3061 ((equal coef-sign -1) '$zerob)
3062 ((equal coef-sign 0) 0)
3063 (t 0)))
3064 ((ratgreaterp num-power den-power)
3065 (cond ((equal coef-sign 1.) '$inf)
3066 ((equal coef-sign -1) '$minf)
3067 ((equal coef-sign 0) nil) ; should never be zero
3068 ((null coef-sign) '$infinity)))
3069 (t coef))))
3071 (defun radlim (e n d)
3072 (prog (nl dl)
3073 (cond ((eq val '$infinity) (throw 'limit nil))
3074 ((eq val '$minf)
3075 (setq nl (m* var -1))
3076 (setq n (subin nl n))
3077 (setq d (subin nl d))
3078 (setq val '$inf))) ;This is the Culprit. Doesn't tell the DATABASE.
3079 (cond ((eq val '$inf)
3080 (setq nl (asymredu n))
3081 (setq dl (asymredu d))
3082 (cond
3083 ((or (rptrouble n) (rptrouble d))
3084 (return (limit (m* (rdsget n) (m^ (rdsget d) -1.)) var val t)))
3085 (t (return (asy nl dl))))))
3086 (setq nl (limit n var val t))
3087 (setq dl (limit d var val t))
3088 (cond ((and (zerop2 nl) (zerop2 dl))
3089 (cond ((or (polyp n) (polyp d))
3090 (return (try-lhospital-quit n d t)))
3091 (t (return (ser0 e n d val)))))
3092 (t (return ($radcan (ratrad (m// n d) n d nl dl)))))))
3094 (defun ratrad (e n d nl dl)
3095 (prog (n1 d1)
3096 (cond ((equal nl 0) (return 0))
3097 ((zerop2 dl)
3098 (setq n1 nl)
3099 (cond ((equal dl 0) (setq d1 '$infinity)) ;No direction Info.
3100 ((eq dl '$zeroa)
3101 (setq d1 '$inf))
3102 ((equal (setq d (behavior d var val)) 1)
3103 (setq d1 '$inf))
3104 ((equal d -1) (setq d1 '$minf))
3105 (t (throw 'limit nil))))
3106 ((zerop2 nl)
3107 (setq d1 dl)
3108 (cond ((equal (setq n (behavior n var val)) 1)
3109 (setq n1 '$zeroa))
3110 ((equal n -1) (setq n1 '$zerob))
3111 (t (setq n1 0))))
3112 (t (return ($radcan (ridofab (subin val e))))))
3113 (return (simplimtimes (list n1 d1)))))
3115 ;;; Limit(log(XXX), var, 0, val), where val is either zerob (limit from below)
3116 ;;; or zeroa (limit from above).
3117 (defun simplimln (expr var val)
3118 (let ((arglim (limit (cadr expr) var val 'think)) (dir))
3119 (cond ((eq arglim '$inf) '$inf) ;log(inf) = inf
3120 ;;log(minf,infinity,zerob) = infinity & log(0) = infinity
3121 ((or (member arglim '($minf $infinity $zerob)))
3122 '$infinity)
3123 ((eq arglim '$zeroa) '$minf) ;log(zeroa) = minf
3124 ;; log(ind) = ind when ind > 0 else und
3125 ((eq arglim '$ind)
3126 (if (eq t (mgrp (cadr expr) 0)) '$ind '$und))
3127 ;; log(und) = und
3128 ((eq arglim '$und) '$und)
3129 ((member arglim '($ind $und)) '$und)
3130 ;; log(1^(-)) = zerob, log(1^(+)) = zeroa & log(1)=0
3131 ((eql arglim 1)
3132 (if (or (eq val '$zerob) (eq var '$zeroa)) val 0))
3133 ;; Special case of arglim = 0
3134 ((eql arglim 0)
3135 (setq dir (behavior (cadr expr) var val))
3136 (cond ((eql dir -1) '$infinity)
3137 ((eql dir 0) '$infinity)
3138 ((eql dir 1) '$minf)))
3139 ;; When arglim is off the negative real axis, use direct substitution
3140 ((off-negative-real-axisp arglim)
3141 (ftake '%log arglim))
3143 ;; We know that arglim is a negative real number, say xx.
3144 ;; When the imaginary part of (cadr expr) near var is negative,
3145 ;; return log(-x) - %i*pi; when the imaginary part of (cadr expr)
3146 ;; near var is positive return log(-x) + %i*pi; and when
3147 ;; we cannot determine the behavior of the imaginary part,
3148 ;; return a nounform. The value of val (either zeroa or zerob)
3149 ;; determines what is meant by "near" (smaller than var when
3150 ;; val is zerob and larger than var when val is zeroa).
3151 (setq dir (behavior ($imagpart (cadr expr)) var val))
3152 (cond ((or (eql dir 1) (eql dir -1))
3153 (add (ftake '%log (mul -1 arglim)) (mul dir '$%i '$%pi)))
3154 (t (throw 'limit nil))))))) ;do a nounform return
3155 (setf (get '%log 'simplim%function) 'simplimln)
3156 (setf (get '%plog 'simplim%function) 'simplimln)
3158 (defun simplim%limit (e x pt)
3159 (declare (ignore e x pt))
3160 (throw 'limit t))
3161 (setf (get '%limit 'simplim%function) 'simplim%limit)
3163 (defun simplim%unit_step (e var val)
3164 (let ((lim (limit (cadr e) var val 'think)))
3165 (cond ((eq lim '$und) '$und)
3166 ((eq lim '$ind) '$ind)
3167 ((eq lim '$zerob) 0)
3168 ((eq lim '$zeroa) 1)
3169 ((not (lenient-realp lim)) (throw 'limit nil)) ;catches infinity too
3170 ;; catches minf & inf cases
3171 ((eq t (mgrp 0 lim)) 0)
3172 ((eq t (mgrp lim 0)) 1)
3173 (t '$ind))))
3174 (setf (get '$unit_step 'simplim%function) 'simplim%unit_step)
3176 (defun simplim%conjugate (e var val)
3177 (let ((lim (limit (cadr e) var val 'think)))
3178 (cond ((off-negative-real-axisp lim)
3179 (ftake '$conjugate lim))
3180 (t (throw 'limit nil)))))
3181 (setf (get '$conjugate 'simplim%function) 'simplim%conjugate)
3183 (defun simplim%imagpart (e var val)
3184 (let ((lim (limit (cadr e) var val 'think)))
3185 (cond ((eq lim '$und) '$und)
3186 ((eq lim '$ind) 0)
3187 ((eq lim '$infinity) (throw 'limit nil))
3188 (t (mfuncall '$imagpart lim)))))
3189 (setf (get '$imagpart 'simplim%function) 'simplim%imagpart)
3190 (setf (get '%imagpart 'simplim%function) 'simplim%imagpart)
3192 (defun simplim%realpart (e var val)
3193 (let ((lim (limit (cadr e) var val 'think)))
3194 (cond ((eq lim '$und) '$und)
3195 ((eq lim '$ind) '$ind)
3196 ((eq lim '$infinity) (throw 'limit nil))
3197 (t (mfuncall '$realpart lim)))))
3198 (setf (get '$realpart 'simplim%function) 'simplim%realpart)
3199 (setf (get '%realpart 'simplim%function) 'simplim%realpart)
3200 ;;; Limit of the Factorial function
3202 (defun simplimfact (expr var val)
3203 (let* ((arglim (limit (cadr expr) var val 'think)) ; Limit of the argument.
3204 (arg2 arglim))
3205 (cond ((eq arglim '$inf) '$inf)
3206 ((member arglim '($minf $infinity $und $ind) :test #'eq) '$und)
3207 ((zerop2 arglim) 1)
3208 ((and (or (maxima-integerp arglim)
3209 (setq arg2 (integer-representation-p arglim)))
3210 (eq ($sign arg2) '$neg))
3211 ;; A negative integer or float or bigfloat representation.
3212 (let ((dir (limit (add (cadr expr) (mul -1 arg2)) var val 'think))
3213 (even (mevenp arg2)))
3214 (cond ((or (and even
3215 (eq dir '$zeroa))
3216 (and (not even)
3217 (eq dir '$zerob)))
3218 '$minf)
3219 ((or (and even
3220 (eq dir '$zerob))
3221 (and (not even)
3222 (eq dir '$zeroa)))
3223 '$inf)
3224 (t (throw 'limit nil)))))
3226 ;; Call simplifier to get value at the limit of the argument.
3227 (simplify (list '(mfactorial) arglim))))))
3228 (setf (get 'mfactorial 'simplim%function) 'simplimfact)
3230 (defun simplim%erf-%tanh (fn arg)
3231 (let ((arglim (limit arg var val 'think))
3232 (ans ())
3233 (rlim ()))
3234 (cond ((eq arglim '$inf) 1)
3235 ((eq arglim '$minf) -1)
3236 ((eq arglim '$infinity)
3237 (destructuring-bind (rpart . ipart)
3238 (trisplit arg)
3239 (setq rlim (limit rpart var origval 'think))
3240 (cond ((eq fn '%tanh)
3241 (cond ((equal rlim '$inf) 1)
3242 ((equal rlim '$minf) -1)))
3243 ((eq fn '%erf)
3244 (setq ans (limit (m* rpart (m^t ipart -1)) var origval 'think))
3245 (setq ans ($asksign (m+ `((mabs) ,ans) -1)))
3246 (cond ((or (eq ans '$pos) (eq ans '$zero))
3247 (cond ((eq rlim '$inf) 1)
3248 ((eq rlim '$minf) -1)
3249 (t '$und)))
3250 (t '$und))))))
3251 ((eq arglim '$und) '$und)
3252 ((member arglim '($zeroa $zerob $ind) :test #'eq) arglim)
3253 ;;;Ignore tanh(%pi/2*%I) and multiples of the argument.
3255 ;; erf (or tanh) of a known value is just erf(arglim).
3256 (simplify (list (ncons fn) arglim))))))
3258 (defun in-domain-of-atan (z)
3259 (setq z (trisplit z)) ; split z into real and imaginary parts
3260 (let ((x (car z)) (y (cdr z))) ;z = x+%i*y
3261 (not
3262 (and
3263 (eq t (meqp x 0)) ;Re(z) = 0
3264 (or (eq t (mgqp -1 y)) ;-1 >= Im(z)
3265 (eq t (mgqp y 1))))))) ; Im(z) >= 1
3267 (defun simplim%atan (e x pt)
3268 (let ((lim (limit (cadr e) x pt 'think)))
3269 (cond ((or (eq lim '$zeroa) (eq lim '$zerob) (eq lim 0) (eq lim '$ind)) lim)
3270 ((or (eq lim '$und) (eq lim '$infinity)) (throw 'limit nil))
3271 ((eq lim '$inf) #$%pi/2$) ;atan(inf) -> %pi/2
3272 ((eq lim '$minf) #$-%pi/2$) ;atan(-inf) -> -%pi/2
3273 ((in-domain-of-atan (ridofab lim)) ; direct substitution
3274 (ftake '%atan (ridofab lim)))
3275 (t (limit ($logarc e) x pt 'think)))))
3276 (setf (get '%atan 'simplim%function) 'simplim%atan)
3278 (defmvar extended-reals
3279 (append *infinitesimals* *infinities* (list '$und '$ind)))
3281 ;; Most instances of atan2 are simplified to atan expressions, but this routine
3282 ;; handles tricky cases such as limit(atan2((x^2-2), x^3-2*x), x, sqrt(2), minus).
3283 ;; Taylor and Gruntz cannot handle the discontinuity at atan(0, -1)
3285 ;; When possible, we want to evaluate the limit of an atan2 expression using
3286 ;; direct substitution--that produces, I think, the least surprising values.
3288 ;; The general simplifier catches atan2(0,0) and it transforms atan2(minf or inf,X)
3289 ;; and atan2(X, minf or inf) into an atan expression, but it doesn't catch
3290 ;; atan2(X, zerob or zeroa) or atan2(zerob or zeroa, X). For the other extended
3291 ;; real (ind,und, or infinity) arguments, the general simplifier gives sign errors.
3293 (defun simplim%atan2 (e v pt)
3294 (let ((y (second e))
3295 (x (third e))
3296 (xlim)
3297 (ylim)
3298 (xlim-z)
3299 (ylim-z)
3300 (q))
3301 (setq xlim (limit x v pt 'think))
3302 (setq ylim (limit y v pt 'think))
3303 (setq xlim-z (ridofab xlim)
3304 ylim-z (ridofab ylim))
3305 ;; For cases for which direct substitution fails, normalize
3306 ;; x & y and try again.
3307 (setq q (cond ((eq xlim '$inf) x)
3308 ((eq xlim '$minf)
3309 (mul -1 x))
3310 ((eq ylim '$inf) y)
3311 ((eq ylim '$minf)
3312 (mul -1 y))
3313 ((and (eq xlim '$zerob) (zerop2 ylim))
3314 (mul -1 x))
3315 ((and (eq xlim '$zeroa) (zerop2 ylim))
3317 ((and (eq ylim '$zerob) (zerop2 xlim))
3318 (mul -1 y))
3319 ((and (eq ylim '$zeroa) (zerop2 xlim))
3321 (t 1)))
3323 (when (not (eql q 1))
3324 (setq x (div x q))
3325 (setq y (div y q))
3326 (setq xlim (limit x v pt 'think))
3327 (setq ylim (limit y v pt 'think))
3328 (setq xlim-z (ridofab xlim)
3329 ylim-z (ridofab ylim)))
3331 (cond
3332 ((and (eq '$zerob ylim) (eq t (mgrp 0 xlim)))
3333 (mul -1 '$%pi))
3334 ((and (eq '$zerob ylim) (eq t (mgrp xlim 0)))
3336 ((and (eq '$zeroa ylim) (eq t (mgrp 0 xlim)))
3337 '$%pi)
3338 ((and (eq '$zeroa ylim) (eq t (mgrp xlim 0)))
3340 ((and (eql xlim 1) (eql ylim '$inf))
3341 (div '$%pi 2))
3342 ((and (eql xlim -1) (eql ylim 0))
3343 '$ind)
3345 ;; Use direct substitution when ylim-z # 0 or xlim-z > 0. We need
3346 ;; to check that xlim-z & ylim-z are real too.
3347 ((and (lenient-realp xlim-z)
3348 (lenient-realp ylim-z)
3349 (or (eq t (mnqp ylim-z 0))
3350 (eq t (mgrp xlim-z 0))))
3351 (ftake '%atan2 ylim-z xlim-z))
3353 (throw 'limit nil)))))
3354 (setf (get '%atan2 'simplim%function) 'simplim%atan2)
3356 (defun simplimsch (sch arg)
3357 (cond ((real-infinityp arg)
3358 (cond ((eq sch '%sinh) arg) (t '$inf)))
3359 ((eq arg '$infinity) '$infinity)
3360 ((eq arg '$ind) '$ind)
3361 ((eq arg '$und) '$und)
3362 ((and (eq sch '%sinh)
3363 (or (eq arg '$zerob) (eq arg '$zeroa)))
3364 arg)
3365 (t (let (($exponentialize t))
3366 (resimplify (list (ncons sch) (ridofab arg)))))))
3368 ;; simple limit of sin and cos
3369 (defun simplimsc (exp fn arg)
3370 (cond ((member arg '($inf $minf $ind) :test #'eq) '$ind)
3371 ((member arg '($und $infinity) :test #'eq)
3372 (throw 'limit ()))
3373 ((member arg '($zeroa $zerob) :test #'eq)
3374 (cond ((eq fn '%sin) arg)
3375 (t (m+ 1 '$zerob))))
3376 ((sincoshk exp
3377 (simplify (list (ncons fn) (ridofab arg)))
3378 fn))))
3380 (defun simplim%tan (arg)
3381 (let ((arglim (limit arg var val 'think)))
3382 (cond
3383 ((member arglim '($inf $minf $ind) :test #'eq)
3384 '$ind)
3385 ((member arglim '($und $infinity) :test #'eq)
3386 (throw 'limit nil))
3388 ;; Write the limit of the argument as c*%pi + rest.
3389 (let*
3390 ((c (or (pip arglim) 0))
3391 (rest (sratsimp (m- arglim (m* '$%pi c))))
3392 (hit-zero))
3393 ;; Check if tan(x) has a zero or pole at x=arglim.
3394 ;; zero: tan(n*%pi + 0*)
3395 ;; pole: tan((2*n+1)*%pi/2 + 0*)
3396 ;; 0* can be $zeroa, $zerob or 0.
3397 (if (and (member rest '(0 $zeroa $zerob) :test #'equal)
3398 (or (setq hit-zero (integerp c))
3399 (and (ratnump c) (equal (caddr c) 2))))
3400 ;; This is a zero or a pole.
3401 ;; Determine on which side of the zero/pole we are.
3402 ;; If rest is $zeroa or $zerob, use that.
3403 ;; Otherwise (rest = 0), try to determine the side
3404 ;; using the behavior of the argument.
3405 (let
3406 ((side (cond ((eq rest '$zeroa) 1)
3407 ((eq rest '$zerob) -1)
3408 (t (behavior arg var val)))))
3409 (if hit-zero
3410 ;; For a zero, if we don't know the side, just return 0.
3411 (cond
3412 ((equal side 1) '$zeroa)
3413 ((equal side -1) '$zerob)
3414 (t 0))
3415 ;; For a pole, we need to know the side.
3416 ;; Otherwise, we can't determine the limit.
3417 (cond
3418 ((equal side 1) '$minf)
3419 ((equal side -1) '$inf)
3420 (t (throw 'limit t)))))
3421 ;; No zero or pole - substitute in the limit of the argument.
3422 (take '(%tan) (ridofab arglim))))))))
3424 (defun simplim%asinh (arg)
3425 (cond ((member arg '($inf $minf $zeroa $zerob $ind $und) :test #'eq)
3426 arg)
3427 ((eq arg '$infinity) '$und)
3428 (t (simplify (list '(%asinh) (ridofab arg))))))
3430 (defun simplim%acosh (arg)
3431 (cond ((equal (ridofab arg) 1) '$zeroa)
3432 ((eq arg '$inf) arg)
3433 ((eq arg '$minf) '$infinity)
3434 ((member arg '($und $ind $infinity) :test #'eq) '$und)
3435 (t (simplify (list '(%acosh) (ridofab arg))))))
3437 (defun simplim%atanh (arg dir)
3438 ;; Compute limit(atanh(x),x,arg). If ARG is +/-1, we need to take
3439 ;; into account which direction we're approaching ARG.
3440 (cond ((zerop2 arg) arg)
3441 ((member arg '($ind $und $infinity $minf $inf) :test #'eq)
3442 '$und)
3443 ((equal (setq arg (ridofab arg)) 1.)
3444 ;; The limit at 1 should be complex infinity because atanh(x)
3445 ;; is complex for x > 1, but inf if we're approaching 1 from
3446 ;; below.
3447 (if (eq dir '$zerob)
3448 '$inf
3449 '$infinity))
3450 ((equal arg -1.)
3451 ;; Same as above, except for the limit is at -1.
3452 (if (eq dir '$zeroa)
3453 '$minf
3454 '$infinity))
3455 (t (simplify (list '(%atanh) arg)))))
3457 (defun simplim%asin (e x pt)
3458 (let ((lim (limit (cadr e) x pt 'think)) (dir) (lim-sgn))
3459 (cond ((member lim '($zeroa $zerob)) lim) ;asin(zeoroa/b) = zeroa/b
3460 ((member lim '($minf '$inf '$infinity)) '$infinity)
3461 ((eq lim '$ind) '$ind) ;asin(ind)=ind
3462 ((eq lim '$und) '$und) ;asin(und)=und
3463 ((in-domain-of-asin lim) ;direct substitution
3464 (ftake '%asin lim))
3466 (setq e (trisplit (cadr e))) ;overwrite e!
3467 (setq dir (behavior (cdr e) x pt))
3468 (setq lim-sgn ($csign (car e))) ;lim-sgn = sign limit(Re(e))
3469 (cond
3470 ((eql dir 0)
3471 (throw 'limit t)) ;unable to find behavior of imaginary part
3473 ;; For the values of asin on the branch cuts, see DLMF 4.23.20 & 4.23.21
3474 ;; Diagram of the values of asin just above and below the branch cuts
3476 ;; asin(x) pi - asin(x)
3477 ;;................ -1 ....0.... 1 ...............
3478 ;; -pi - asin(x) asin(x)
3480 ;; Let's start in northwest and rotate counterclockwise:
3481 ((and (eq '$neg lim-sgn) (eq dir 1))
3482 (ftake '%asin lim))
3483 ((and (eq '$pos lim-sgn) (eq dir 1))
3484 (sub '$%pi (ftake '%asin lim)))
3485 ((and (eq '$pos lim-sgn) (eq dir -1))
3486 (ftake '%asin lim))
3487 ((and (eq '$neg lim-sgn) (eq dir -1))
3488 (sub (mul -1 '$%pi) (ftake '%asin lim)))
3490 ;; unable to find sign of real part of lim.
3491 (throw 'limit t)))))))
3492 (setf (get '%asin 'simplim%function) 'simplim%asin)
3494 (defun simplim%acos (e x pt)
3495 (let ((lim (limit (cadr e) x pt 'think)) (dir) (lim-sgn))
3496 (cond ((in-domain-of-asin lim) ;direct substitution
3497 (ftake '%acos lim))
3498 ((member lim '($und $ind $inf $minf $infinity)) ;boundary cases
3499 '$und)
3501 (setq e (trisplit (cadr e))) ;overwrite e!
3502 (setq dir (behavior (cdr e) x pt))
3503 (setq lim-sgn ($csign lim))
3504 (cond
3505 ((eql dir 0)
3506 (throw 'limit t)) ;unable to find behavior of imaginary part
3507 ;; for the values of acos on the branch cuts, see DLMF 4.23.24 & 4.23.25
3508 ;; http://dlmf.nist.gov/4.23.E24
3509 ((or (eq '$pos lim-sgn) (eq '$neg lim-sgn))
3510 ;; continuous from above
3511 (if (eql dir 1) (ftake '%acos lim) (sub (mul 2 '$%pi) (ftake '%acos lim))))
3513 ;; unable to find sign of real part of lim.
3514 (throw 'limit t)))))))
3515 (setf (get '%acos 'simplim%function) 'simplim%acos)
3517 ;; Limit of an %integrate expression. For a definite integral
3518 ;; integrate(ee,var,a,b), when ee is free of the limit variable
3519 (defun simplim%integrate (e x pt)
3520 (let* ((ee (second e)) ;ee = integrand
3521 (var (third e)) ;integration variable
3522 (a (fourth e)) ;lower limit or nil if indefinite
3523 (b (fifth e)) ;lower limit or nil if indefinite
3524 (alim) (blim))
3525 (cond ((and a b ($freeof x ee) ($freeof x var))
3526 (setq alim (limit a x pt 'think))
3527 (setq blim (limit b x pt 'think))
3528 (if (and (lenient-extended-realp alim)
3529 (lenient-extended-realp blim)
3530 (not (eq alim '$infinity))
3531 (not (eq blim '$infinity)))
3532 (ftake '%integrate ee var alim blim)
3533 (throw 'limit t)))
3535 (throw 'limit t)))))
3536 (setf (get '%integrate 'simplim%function) 'simplim%integrate)
3538 (defun subftake (op subarg arg)
3539 (simplifya (subfunmake op subarg arg) t))
3541 (defun off-one-to-inf (z)
3542 (setq z (trisplit z)) ; split z into x+%i*y
3544 (eq t (mnqp (cdr z) 0)) ; y # 0
3545 (eq t (mgrp 1 (car z))))) ; x < 1
3547 (defun simplim%li (expr x pt)
3548 (let ((n (car (subfunsubs expr))) (e (car (subfunargs expr))))
3549 (cond ((freeof x n)
3550 (setq e (limit e x pt 'think))
3551 (cond ((and (eq e '$minf) (integerp n) (>= n 2))
3552 '$minf)
3553 ((and (eq e '$inf) (integerp n) (>= n 2))
3554 '$infinity)
3555 ((or (eql (ridofab e) 1) (and (not (extended-real-p e)) (off-one-to-inf e)))
3556 ;; Limit of li[s](1) can be evaluated by just
3557 ;; substituting in 1.
3558 ;; Same for li[s](x) when x is < 1.
3559 (subftake '$li (list n) (list e)))
3560 (t (throw 'limit nil))))
3561 ;; Claim ignorance when order depends on limit variable.
3562 (t (throw 'limit nil)))))
3564 (setf (get '$li 'simplim%function) 'simplim%li)
3565 (setf (get '%li 'simplim%function) 'simplim%li)
3567 (defun simplim$psi (order arg val)
3568 (if (and (not (equal (length order) 1))
3569 (not (equal (length arg) 1)))
3570 (throw 'limit ())
3571 (setq order (car order)
3572 arg (car arg)))
3573 (cond ((equal order 0)
3574 (destructuring-bind (rpart . ipart)
3575 (trisplit arg)
3576 (cond ((not (equal ipart 0)) (throw 'limit ()))
3577 (t (setq rpart (limit rpart var val 'think))
3578 (cond ((eq rpart '$zeroa) '$minf)
3579 ((eq rpart '$zerob) '$inf)
3580 ((eq rpart '$inf) '$inf)
3581 ((eq rpart '$minf) '$und)
3582 ((equal (getsignl rpart) -1) (throw 'limit ()))
3583 (t (simplify (subfunmake '$psi (list order)
3584 (list rpart)))))))))
3585 ((and (integerp order) (> order 0)
3586 (equal (limit arg var val 'think) '$inf))
3587 (cond ((mevenp order) '$zerob)
3588 ((moddp order) '$zeroa)
3589 (t (throw 'limit ()))))
3590 (t (throw 'limit ()))))
3592 (defun simplim%inverse_jacobi_ns (arg m)
3593 (if (or (eq arg '$inf) (eq arg '$minf))
3595 `((%inverse_jacobi_ns) ,arg ,m)))
3597 (defun simplim%inverse_jacobi_nc (arg m)
3598 (if (or (eq arg '$inf) (eq arg '$minf))
3599 `((%elliptic_kc) ,m)
3600 `((%inverse_jacobi_nc) ,arg ,m)))
3602 (defun simplim%inverse_jacobi_sc (arg m)
3603 (if (or (eq arg '$inf) (eq arg '$minf))
3604 `((%elliptic_kc) ,m)
3605 `((%inverse_jacobi_sc) ,arg ,m)))
3607 (defun simplim%inverse_jacobi_dc (arg m)
3608 (if (or (eq arg '$inf) (eq arg '$minf))
3609 `((%elliptic_kc) ,m)
3610 `((%inverse_jacobi_dc) ,arg ,m)))
3612 (defun simplim%inverse_jacobi_cs (arg m)
3613 (if (or (eq arg '$inf) (eq arg '$minf))
3615 `((%inverse_jacobi_cs) ,arg ,m)))
3617 (defun simplim%inverse_jacobi_ds (arg m)
3618 (if (or (eq arg '$inf) (eq arg '$minf))
3620 `((%inverse_jacobi_ds) ,arg ,m)))
3622 (defun simplim%signum (e x pt)
3623 (let ((e (limit (cadr e) x pt 'think)) (sgn))
3624 (cond ((eq '$minf e) -1)
3625 ((eq '$inf e) 1)
3626 ((eq '$infinity e) '$und)
3627 ((eq '$ind e) '$ind)
3628 ((eq '$und e) e)
3629 ((eq '$zerob e) -1)
3630 ((eq '$zeroa e) 1)
3632 (setq sgn (mnqp e 0))
3633 (cond ((eq t sgn) (ftake '%signum e))
3634 (t (throw 'limit nil))))))) ; don't know
3635 (setf (get '%signum 'simplim%function) 'simplim%signum)
3637 ;; more functions for limit to handle
3639 (defun lfibtophi (e)
3640 (cond ((not (involve e '($fib))) e)
3641 ((eq (caar e) '$fib)
3642 (let ((lnorecurse t))
3643 ($fibtophi (list '($fib) (lfibtophi (cadr e))) lnorecurse)))
3644 (t (cons (car e)
3645 (mapcar #'lfibtophi (cdr e))))))
3647 ;;; FOLLOWING CODE MAKES $LDEFINT WORK
3649 (defmfun $ldefint (exp var ll ul &aux $logabs ans a1 a2)
3650 (setq $logabs t ans (sinint exp var)
3651 a1 (toplevel-$limit ans var ul '$minus)
3652 a2 (toplevel-$limit ans var ll '$plus))
3653 (and (member a1 '($inf $minf $infinity $und $ind) :test #'eq)
3654 (setq a1 (nounlimit ans var ul)))
3655 (and (member a2 '($inf $minf $infinity $und $ind) :test #'eq)
3656 (setq a2 (nounlimit ans var ll)))
3657 ($expand (m- a1 a2)))
3659 (defun nounlimit (exp var val)
3660 (setq exp (restorelim exp))
3661 (nconc (list '(%limit) exp var (ridofab val))
3662 (cond ((eq val '$zeroa) '($plus))
3663 ((eq val '$zerob) '($minus)))))
3665 ;; substitute inside noun form of %derivative
3666 ;; for cases such as limit('diff(x+2,x), x, 1)
3667 ;; -> limit('diff(xx+3), xx, 0)
3669 ;; maxima-substitute with *atp* skips over %derivative
3671 ;; substitutes diff(f(realvar), realvar, n)
3672 ;; -> diff(f(var+val), var, n)
3673 (defun derivative-subst (exp val var realvar)
3674 (cond ((atom exp) exp)
3675 ((eq '%derivative (caar exp))
3676 (cons
3677 (car exp)
3678 (cons ;; the function being differentiated
3679 (maxima-substitute (m+ val var) realvar (cadr exp))
3680 (cons ;; the var of differentiation
3681 (maxima-substitute var realvar (caddr exp))
3682 (cdddr exp))))) ;; the order of the derivative
3683 (t (cons (car exp)
3684 (mapcar (lambda (x) (derivative-subst x val var realvar))
3685 (cdr exp))))))
3687 (defun oscip (e)
3688 (or (involve e '(%sin %cos %tan))
3689 (among '$%i (%einvolve e))))
3691 ;; Like OSCIP, but the dependency on VAR is explicit (second arg).
3692 ;; Use this instead when possible.
3693 (defun oscip-var (e var1)
3694 (or (involve-var e var1 '(%sin %cos %tan))
3695 (among '$%i (%einvolve-var e var1))))
3697 (defun %einvolve (e)
3698 (when (among '$%e e) (%einvolve01 e)))
3700 (defun %einvolve01 (e)
3701 (cond ((atom e) nil)
3702 ((mnump e) nil)
3703 ((and (mexptp e)
3704 (eq (cadr e) '$%e)
3705 (among var (caddr e)))
3706 (caddr e))
3707 (t (some #'%einvolve (cdr e)))))
3709 ;; Just like %EINVOLVE, except the dependency on VAR is explicit
3710 ;; (second arg here). Use this instead when possible.
3711 (defun %einvolve-var (e var1)
3712 (flet ((%einvolve01-var (e)
3713 ;; A copy of %ENVOLVE01, but for %EINVOLVE-VAR.
3714 (cond ((atom e)
3715 nil)
3716 ((mnump e)
3717 nil)
3718 ((and (mexptp e)
3719 (eq (cadr e) '$%e)
3720 (among var1 (caddr e)))
3721 (caddr e))
3722 (t (some #'(lambda (ee)
3723 (%einvolve-var ee var1))
3724 (cdr e))))))
3725 (when (among '$%e e)
3726 (%einvolve01-var e))))
3729 (declare-top (unspecial *indicator exp var val origval taylored
3730 $tlimswitch logcombed lhp? lhcount))
3733 ;; GRUNTZ ALGORITHM
3735 ;; Dominik Gruntz
3736 ;; "On Computing Limits in a Symbolic Manipulation System"
3737 ;; PhD Dissertation ETH Zurich 1996
3739 ;; The algorithm identifies the most rapidly varying (MRV) subexpression,
3740 ;; replaces it with a new variable w, rewrites the expression in terms
3741 ;; of the new variable, and then repeats.
3743 ;; The algorithm doesn't handle oscillating functions, so it can't do things like
3744 ;; limit(sin(x)/x, x, inf).
3746 ;; To handle limits involving functions like gamma(x) and erf(x), the
3747 ;; gruntz algorithm requires them to be written in terms of asymptotic
3748 ;; expansions, which maxima cannot currently do.
3750 ;; The algorithm assumes that everything is real, so it can't
3751 ;; currently handle limit((-2)^x, x, inf).
3753 ;; This is one of the methods used by maxima's $limit.
3754 ;; It is also directly available to the user as $gruntz.
3757 ;; most rapidly varying subexpression of expression exp with respect to limit variable var.
3758 ;; returns a list of subexpressions which are in the same MRV equivalence class.
3759 (defun mrv (exp var)
3760 (cond ((freeof var exp)
3761 nil)
3762 ((eq var exp)
3763 (list var))
3764 ((mtimesp exp)
3765 (mrv-max (mrv (cadr exp) var)
3766 (mrv (m*l (cddr exp)) var)
3767 var))
3768 ((mplusp exp)
3769 (mrv-max (mrv (cadr exp) var)
3770 (mrv (m+l (cddr exp)) var)
3771 var))
3772 ((mexptp exp)
3773 (cond ((freeof var (caddr exp))
3774 (mrv (cadr exp) var))
3775 ((member (limitinf (logred exp) var) '($inf $minf) :test #'eq)
3776 (mrv-max (list exp) (mrv (caddr exp) var) var))
3777 (t (mrv-max (mrv (cadr exp) var) (mrv (caddr exp) var) var))))
3778 ((mlogp exp)
3779 (mrv (cadr exp) var))
3780 ((equal (length (cdr exp)) 1)
3781 (mrv (cadr exp) var))
3782 ((equal (length (cdr exp)) 2)
3783 (mrv-max (mrv (cadr exp) var)
3784 (mrv (caddr exp) var)
3785 var))
3786 (t (tay-error "mrv not implemented" exp))))
3788 ;; takes two lists of expressions, f and g, and limit variable var.
3789 ;; members in each list are assumed to be in same MRV equivalence
3790 ;; class. returns MRV set of the union of the inputs - either f or g
3791 ;; or the union of f and g.
3792 (defun mrv-max (f g var)
3793 (prog ()
3794 (cond ((not f)
3795 (return g))
3796 ((not g)
3797 (return f))
3798 ((intersection f g)
3799 (return (union f g))))
3800 (let ((c (mrv-compare (car f) (car g) var)))
3801 (cond ((eq c '>)
3802 (return f))
3803 ((eq c '<)
3804 (return g))
3805 ((eq c '=)
3806 (return (union f g)))
3807 (t (merror "MRV-MAX: expected '>' '<' or '='; found: ~M" c))))))
3809 (defun mrv-compare (a b var)
3810 (let ((c (limitinf (m// `((%log) ,a) `((%log) ,b)) var)))
3811 (cond ((equal c 0)
3813 ((member c '($inf $minf) :test #'eq)
3815 (t '=))))
3817 ;; rewrite expression exp by replacing members of MRV set omega with
3818 ;; expressions in terms of new variable wsym. return cons pair of new
3819 ;; version of exp and the log of the new variable wsym.
3820 (defun mrv-rewrite (exp omega var wsym)
3821 (setq omega (stable-sort omega (lambda (x y) (> (length (mrv x var))
3822 (length (mrv y var))))));FIXME consider a total order function with #'sort
3823 (let* ((g (car (last omega)))
3824 (logg (logred g))
3825 (sig (equal (mrv-sign logg var) 1))
3826 (w (if sig (m// 1 wsym) wsym))
3827 (logw (if sig (m* -1 logg) logg)))
3828 (mapcar (lambda (x y)
3829 ;;(mtell "y:~M x:~M exp:~M~%" y x exp)
3830 (setq exp (syntactic-substitute y x exp)))
3831 omega
3832 (mapcar (lambda (f) ;; rewrite each element of omega
3833 (let* ((logf (logred f))
3834 (c (mrv-leadterm (m// logf logg) var nil)))
3835 (cond ((not (equal (cadr c) 0))
3836 (merror "MRV-REWRITE: expected leading term to be constant in ~M" c)))
3837 ;;(mtell "logg: ~M logf: ~M~%" logg logf)
3838 (m* (m^ w (car c))
3839 (m^ '$%e (m- logf
3840 (m* (car c) logg))))))
3841 omega))
3842 (cons exp logw)))
3844 ;;; if log w(x) = h(x), rewrite all subexpressions of the form
3845 ;;; log(f(x)) as log(w^-c f(x)) + c h(x) with c the unique constant
3846 ;;; such that w^-c f(x) is strictly less rapidly varying than w.
3847 (defun mrv-rewrite-logs (exp wsym logw)
3848 (cond ((atom exp) exp)
3849 ((and (mlogp exp)
3850 (not (freeof wsym exp)))
3851 (let* ((f (cadr exp))
3852 (c ($lopow (calculate-series f wsym)
3853 wsym)))
3854 (m+ (list (car exp)
3855 (m* (m^ wsym (m- c))
3856 (mrv-rewrite-logs f wsym logw)))
3857 (m* c logw))))
3859 (cons (car exp)
3860 (mapcar (lambda (e)
3861 (mrv-rewrite-logs e wsym logw))
3862 (cdr exp))))))
3864 ;; returns list of two elements: coeff and exponent of leading term of exp,
3865 ;; after rewriting exp in term of its MRV set omega.
3866 (defun mrv-leadterm (exp var omega)
3867 (prog ((new-omega ()))
3868 (cond ((freeof var exp)
3869 (return (list exp 0))))
3870 (dolist (term omega)
3871 (cond ((subexp exp term)
3872 (push term new-omega))))
3873 (setq omega new-omega)
3874 (cond ((not omega)
3875 (setq omega (mrv exp var))))
3876 (cond ((member var omega :test #'eq)
3877 (let* ((omega-up (mrv-moveup omega var))
3878 (e-up (car (mrv-moveup (list exp) var)))
3879 (mrv-leadterm-up (mrv-leadterm e-up var omega-up)))
3880 (return (mrv-movedown mrv-leadterm-up var)))))
3881 (destructuring-let* ((wsym (gensym "w"))
3883 coef
3884 ((f . logw) (mrv-rewrite exp omega var wsym))
3885 (series (calculate-series (mrv-rewrite-logs f wsym logw)
3886 wsym)))
3887 (setq series (maxima-substitute logw `((%log) ,wsym) series))
3888 (setq lo ($lopow series wsym))
3889 (when (or (not ($constantp lo))
3890 (not (free series '%derivative)))
3891 ;; (mtell "series: ~M lo: ~M~%" series lo)
3892 (tay-error "error in series expansion" f))
3893 (setq coef ($coeff series wsym lo))
3894 (when (not (free coef wsym))
3895 (tay-error "MRV-LEADTERM: failed to extract leading coefficient; obtained" coef))
3896 ;;(mtell "exp: ~M f: ~M~%" exp f)
3897 ;;(mtell "series: ~M~%coeff: ~M~%pow: ~M~%" series coef lo)
3898 (return (list coef lo)))))
3900 (defun mrv-moveup (l var)
3901 (mapcar (lambda (exp)
3902 (simplify-log-of-exp
3903 (syntactic-substitute `((mexpt) $%e ,var) var exp)))
3906 (defun mrv-movedown (l var)
3907 (mapcar (lambda (exp) (syntactic-substitute `((%log simp) ,var) var exp))
3910 ;; test whether sub is a subexpression of exp
3911 (defun subexp (exp sub)
3912 (let ((dummy (gensym)))
3913 (putprop dummy t 'internal)
3914 (not (alike1 (maxima-substitute dummy
3916 exp)
3917 exp))))
3919 ;; Generate $lhospitallim terms of taylor expansion.
3920 ;; Ideally we would use a lazy series representation that generates
3921 ;; more terms as higher order terms cancel.
3922 (defun calculate-series (exp var)
3923 (let ((cntx ($supcontext)) ($taylor_simplifier #'extra-simp))
3924 ($activate cntx)
3925 (unwind-protect
3926 (progn
3927 (mfuncall '$assume (ftake 'mgreaterp var 0))
3928 (putprop var t 'internal); keep var from appearing in questions to user
3929 ($taylor exp var 0 $lhospitallim))
3930 (remprop var 'internal)
3931 ($killcontext cntx))))
3933 (defun mrv-sign (exp var)
3934 (cond ((freeof var exp)
3935 (let ((sign ($sign ($radcan exp))))
3936 (cond ((eq sign '$zero)
3938 ((eq sign '$pos)
3940 ((eq sign '$neg)
3942 (t (tay-error " cannot determine mrv-sign" exp)))))
3943 ((eq exp var)
3945 ((mtimesp exp)
3946 (* (mrv-sign (cadr exp) var)
3947 (mrv-sign (m*l (cddr exp)) var)))
3948 ((and (mexptp exp)
3949 (equal (mrv-sign (cadr exp) var) 1))
3951 ((mlogp exp)
3952 (cond ((equal (mrv-sign (cadr exp) var) -1)
3953 (tay-error " complex expression in gruntz limit" exp)))
3954 (mrv-sign (m+ -1 (cadr exp)) var))
3955 ((mplusp exp)
3956 (mrv-sign (limitinf exp var) var))
3957 (t (tay-error " cannot determine mrv-sign" exp))))
3959 ;; gruntz algorithm for limit of exp as var goes to positive infinity
3960 (defun limitinf (exp var)
3961 (prog (($exptsubst nil))
3962 (cond ((freeof var exp)
3963 (return exp)))
3964 (destructuring-let* ((c0-e0 (mrv-leadterm exp var nil))
3965 (c0 (car c0-e0))
3966 (e0 (cadr c0-e0))
3967 (sig (mrv-sign e0 var)))
3968 (cond ((equal sig 1)
3969 (return 0))
3970 ((equal sig -1)
3971 (cond ((equal (mrv-sign c0 var) 1)
3972 (return '$inf))
3973 ((equal (mrv-sign c0 var) -1)
3974 (return '$minf))))
3975 ((equal sig 0)
3976 (if (equal exp c0)
3977 ;; example: gruntz(n^n/(n^n+(n-1)^n), n, inf);
3978 (tay-error " infinite recursion in limitinf" exp))
3979 (return (limitinf c0 var)))))))
3981 ;; user-level function equivalent to $limit.
3982 ;; direction must be specified if limit point is not infinite
3983 ;; The arguments are checked and a failure of taylor is catched.
3985 (defmfun $gruntz (expr var val &rest rest)
3986 (let (ans dir)
3987 (when (> (length rest) 1)
3988 (merror
3989 (intl:gettext "gruntz: too many arguments; expected just 3 or 4")))
3990 (setq dir (car rest))
3991 (when (and (not (member val '($inf $minf $zeroa $zerob)))
3992 (not (member dir '($plus $minus))))
3993 (merror
3994 (intl:gettext "gruntz: direction must be 'plus' or 'minus'")))
3995 (setq ans
3996 (catch 'taylor-catch
3997 (let ((silent-taylor-flag t))
3998 (gruntz1 expr var val dir))))
3999 (if (or (null ans) (eq ans t))
4000 (if dir
4001 `(($gruntz simp) ,expr ,var, val ,dir)
4002 `(($gruntz simp) ,expr ,var ,val))
4003 ans)))
4005 ;; Additional simplifications for the limit function. Specifically:
4006 ;; (a) replace every mapatom that is declared to be zero by zero
4007 ;; (b) dispatch radcan on expressions of the form (positive integer)^XXX
4008 ;; (c) log(negative number) --> log(-negative number) + %i*%pi
4009 ;; (d) apply cos(X)^2 + sin(X)^2 --> 1, when X depends on var
4010 ;; (e) convert, gamma functions, binomial coefficients, and beta functions to
4011 ;; factorial form
4012 ;; (f) do some reciprocial function transformations; for example
4013 ;; csc(X) --> 1/sin(X)
4014 ;; (g) do transformations similar to acsc(X) --> asin(1/X).
4015 ;; (h) convert fibonacci functions to power form.
4016 ;; The mechanism (a) isn't perfect--if a+b is declared to zero, it doesn't
4017 ;; simplify a+b+c to c, for example.
4019 ;; This should be moved to the jacobi function code. And likely, we should
4020 ;; set the reciprocal property for the other jacobi functions.
4021 (mapcar #'(lambda (q) (setf (get (car q) 'recip) (cdr q)))
4022 '((%jacobi_nc . %jacobi_cn)
4023 (%jacobi_ns . %jacobi_sn)
4024 (%jacobi_cs . %jacobi_sc)
4025 (%jacobi_ds . %jacobi_sd)
4026 (%jacobi_dc . %jacobi_cd)))
4028 (defun extra-simp (e)
4029 (declare (special var))
4030 (let ((var-present (not (freeof var e))))
4031 (cond ((extended-real-p e) e) ;we don't want to call sign on ind, so catch this
4032 (($mapatom e) ;if e is declared zero, return 0; otherwise e
4033 (if (eq '$zero ($csign e)) 0 e))
4034 ;; dispatch radcan on (positive integer)^Y
4035 ((and (mexptp e) (integerp (cadr e)) (> (cadr e) 0))
4036 ($radcan (ftake 'mexpt (cadr e) (extra-simp (caddr e)))))
4037 ;; log(negative number) --> log(-negative number) + %i*%pi. This is
4038 ;; needed for a nice result for integrate(x^3/(exp(x)-1),x,0,inf), for
4039 ;; example.
4040 ((and (eq '%log (caar e)) ($numberp (cadr e)) (eq t (mgrp 0 (cadr e))))
4041 (add (ftake '%log (mul -1 (cadr e))) (mul '$%i '$%pi)))
4042 ;; When e isn't freeof var and e is a sum, map extra-simp over the
4043 ;; summands, add the results, and apply sin-sq-cos-sq-sub.
4044 ((and var-present (mplusp e))
4045 (sin-sq-cos-sq-sub (fapply 'mplus (mapcar #'extra-simp (cdr e))) var))
4046 ;; Convert gamma functions to factorials. Eventually, we should convert
4047 ;; factorials to gamma functions, I think (BW).
4048 ((and var-present (eq '%gamma (caar e)))
4049 (ftake 'mfactorial (extra-simp (sub (cadr e) 1))))
4050 ;; Exponentialize the hyperbolic functions. It might be nicer to not do
4051 ;; this, but without this we get an error for limit(diff(log(tan(%pi/2*tanh(x))),x),x,inf).
4052 ((and var-present (member (caar e) (list '%sinh '%cosh '%tanh '%sech '%csch '%coth)))
4053 (extra-simp ($exponentialize e)))
4054 ;; When X depends on var, apply reciprocal function identities such as
4055 ;; csc(X) --> 1/sin(X). Specifially, do this for operators '%sec, '%csc,
4056 ;; '%cot, '%jacobi_nc, '%jacobi_ns, %jacobi_cs, %jacobi_ds, and %jacobi_dc.
4057 ;; Since the hyperbolics are exponentialized, we don't do this for the
4058 ;; hyperbolics.
4059 ((and var-present (member (caar e)
4060 (list '%sec '%csc '%cot '%jacobi_nc '%jacobi_ns '%jacobi_cs '%jacobi_ds '%jacobi_dc)))
4061 (div 1 (fapply (get (caar e) 'recip) (mapcar #'extra-simp (cdr e)))))
4062 ;; When X or Y depends on var, convert binomial(X,Y) to factorial form.
4063 ;; Same for beta(x,y). Again, I think it would be better to convert to
4064 ;; gamma function form.
4065 ((and var-present (member (caar e) (list '%binomial '%beta)))
4066 (extra-simp ($makefact e)))
4067 ;; When X depends on var, do acsc(X) --> asin(1/X). Do the same
4068 ;; for asec, acot, acsch, asech, and acoth.
4069 ((and var-present (member (caar e) '(%acsc %asec %acot %acsch %asech %acoth)))
4070 (ftake (get (get (get (caar e) '$inverse) 'recip) '$inverse)
4071 (div 1 (extra-simp (cadr e)))))
4072 ;; When X depends on var, convert fib(X) to its power form.
4073 ((and var-present (eq '$fib (caar e)))
4074 (extra-simp ($fibtophi e)))
4075 (($subvarp (mop e)) ;subscripted function
4076 (subfunmake
4077 (subfunname e)
4078 (mapcar #'extra-simp (subfunsubs e))
4079 (mapcar #'extra-simp (subfunargs e))))
4080 (t (fapply (caar e) (mapcar #'extra-simp (cdr e)))))))
4082 ;; Call extra-simp followed by a call to resimplify. This is analogus to
4083 ;; sratsimp.
4084 (defun resimp-extra-simp (e) (resimplify (extra-simp e)))
4086 ;; This function is for internal use in $limit.
4088 ;; The function gruntz1 standardizes the limit point to inf and the limit variable
4089 ;; to a gensym. Since the limit point is possibly altered by this function, we
4090 ;; need to make the appropriate assumptions on the limit variable. This is done
4091 ;; in a supcontext.
4092 (defun gruntz1 (exp var val &rest rest)
4093 (cond ((> (length rest) 1)
4094 (merror (intl:gettext "gruntz: too many arguments; expected just 3 or 4"))))
4095 (let (($logexpand t) ; gruntz needs $logexpand T
4096 (newvar (gensym "w"))
4097 (dir (car rest)))
4098 (putprop newvar t 'internal); keep var from appearing in questions to user
4099 (cond ((eq val '$inf)
4100 (setq exp (maxima-substitute newvar var exp)))
4101 ((eq val '$minf)
4102 (setq exp (maxima-substitute (m* -1 newvar) var exp)))
4103 ((eq val '$zeroa)
4104 (setq exp (maxima-substitute (m// 1 newvar) var exp)))
4105 ((eq val '$zerob)
4106 (setq exp (maxima-substitute (m// -1 newvar) var exp)))
4107 ((eq dir '$plus)
4108 (setq exp (maxima-substitute (m+ val (m// 1 newvar)) var exp)))
4109 ((eq dir '$minus)
4110 (setq exp (maxima-substitute (m+ val (m// -1 newvar)) var exp)))
4111 (t (merror (intl:gettext "gruntz: direction must be 'plus' or 'minus'; found: ~M") dir)))
4112 (let ((cx ($supcontext)))
4113 (unwind-protect
4114 (progn
4115 (mfuncall '$assume (ftake 'mlessp *large-positive-number* newvar)) ; *large-positive-number* < newvar
4116 (mfuncall '$assume (ftake 'mlessp 0 'lim-epsilon)) ; 0 < lim-epsilon
4117 (mfuncall '$assume (ftake 'mlessp *large-positive-number* 'prin-inf)) ; *large-positive-number* < prin-inf
4118 (mfuncall '$activate cx) ;not sure this is needed, but OK
4119 (setq exp (resimplify exp)) ;simplify in new context
4120 (setq exp (resimp-extra-simp (sratsimp exp))) ;additional simplifications
4121 (limitinf exp newvar)) ;compute & return limit
4122 ($killcontext cx))))) ;kill context & forget all new facts.
4124 ;; substitute y for x in exp
4125 ;; similar to maxima-substitute but does not simplify result
4126 (defun syntactic-substitute (y x exp)
4127 (cond ((alike1 x exp) y)
4128 ((atom exp) exp)
4129 (t (cons (car exp)
4130 (mapcar (lambda (exp)
4131 (syntactic-substitute y x exp))
4132 (cdr exp))))))
4134 ;; log(exp(subexpr)) -> subexpr
4135 ;; without simplifying entire exp
4136 (defun simplify-log-of-exp (exp)
4137 (cond ((atom exp) exp)
4138 ((and (mlogp exp)
4139 (mexptp (cadr exp))
4140 (eq '$%e (cadadr exp)))
4141 (caddr (cadr exp)))
4142 (t (cons (car exp)
4143 (mapcar #'simplify-log-of-exp
4144 (cdr exp))))))