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