calc-poly.el 39 KB
Newer Older
1 2
;;; calc-poly.el --- polynomial functions for Calc

Paul Eggert's avatar
Paul Eggert committed
3
;; Copyright (C) 1990-1993, 2001-2018 Free Software Foundation, Inc.
4 5

;; Author: David Gillespie <daveg@synaptics.com>
Eli Zaretskii's avatar
Eli Zaretskii committed
6 7 8

;; This file is part of GNU Emacs.

9
;; GNU Emacs is free software: you can redistribute it and/or modify
10
;; it under the terms of the GNU General Public License as published by
11 12
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
13

Eli Zaretskii's avatar
Eli Zaretskii committed
14
;; GNU Emacs is distributed in the hope that it will be useful,
15 16 17 18 19
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
20
;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
Eli Zaretskii's avatar
Eli Zaretskii committed
21

22
;;; Commentary:
Eli Zaretskii's avatar
Eli Zaretskii committed
23

24
;;; Code:
Eli Zaretskii's avatar
Eli Zaretskii committed
25 26 27

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

Jay Belanger's avatar
Jay Belanger committed
28
(require 'calc-ext)
Eli Zaretskii's avatar
Eli Zaretskii committed
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
(require 'calc-macs)

(defun calcFunc-pcont (expr &optional var)
  (cond ((Math-primp expr)
	 (cond ((Math-zerop expr) 1)
	       ((Math-messy-integerp expr) (math-trunc expr))
	       ((Math-objectp expr) expr)
	       ((or (equal expr var) (not var)) 1)
	       (t expr)))
	((eq (car expr) '*)
	 (math-mul (calcFunc-pcont (nth 1 expr) var)
		   (calcFunc-pcont (nth 2 expr) var)))
	((eq (car expr) '/)
	 (math-div (calcFunc-pcont (nth 1 expr) var)
		   (calcFunc-pcont (nth 2 expr) var)))
	((and (eq (car expr) '^) (Math-natnump (nth 2 expr)))
	 (math-pow (calcFunc-pcont (nth 1 expr) var) (nth 2 expr)))
	((memq (car expr) '(neg polar))
	 (calcFunc-pcont (nth 1 expr) var))
	((consp var)
	 (let ((p (math-is-polynomial expr var)))
	   (if p
	       (let ((lead (nth (1- (length p)) p))
		     (cont (math-poly-gcd-list p)))
		 (if (math-guess-if-neg lead)
		     (math-neg cont)
		   cont))
	     1)))
	((memq (car expr) '(+ - cplx sdev))
	 (let ((cont (calcFunc-pcont (nth 1 expr) var)))
	   (if (eq cont 1)
	       1
	     (let ((c2 (calcFunc-pcont (nth 2 expr) var)))
	       (if (and (math-negp cont)
			(if (eq (car expr) '-) (math-posp c2) (math-negp c2)))
		   (math-neg (math-poly-gcd cont c2))
		 (math-poly-gcd cont c2))))))
	(var expr)
67
	(t 1)))
Eli Zaretskii's avatar
Eli Zaretskii committed
68 69 70 71 72

(defun calcFunc-pprim (expr &optional var)
  (let ((cont (calcFunc-pcont expr var)))
    (if (math-equal-int cont 1)
	expr
73
      (math-poly-div-exact expr cont var))))
Eli Zaretskii's avatar
Eli Zaretskii committed
74 75 76 77 78 79

(defun math-div-poly-const (expr c)
  (cond ((memq (car-safe expr) '(+ -))
	 (list (car expr)
	       (math-div-poly-const (nth 1 expr) c)
	       (math-div-poly-const (nth 2 expr) c)))
80
	(t (math-div expr c))))
Eli Zaretskii's avatar
Eli Zaretskii committed
81 82 83 84 85 86 87

(defun calcFunc-pdeg (expr &optional var)
  (if (Math-zerop expr)
      '(neg (var inf var-inf))
    (if var
	(or (math-polynomial-p expr var)
	    (math-reject-arg expr "Expected a polynomial"))
88
      (math-poly-degree expr))))
Eli Zaretskii's avatar
Eli Zaretskii committed
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105

(defun math-poly-degree (expr)
  (cond ((Math-primp expr)
	 (if (eq (car-safe expr) 'var) 1 0))
	((eq (car expr) 'neg)
	 (math-poly-degree (nth 1 expr)))
	((eq (car expr) '*)
	 (+ (math-poly-degree (nth 1 expr))
	    (math-poly-degree (nth 2 expr))))
	((eq (car expr) '/)
	 (- (math-poly-degree (nth 1 expr))
	    (math-poly-degree (nth 2 expr))))
	((and (eq (car expr) '^) (natnump (nth 2 expr)))
	 (* (math-poly-degree (nth 1 expr)) (nth 2 expr)))
	((memq (car expr) '(+ -))
	 (max (math-poly-degree (nth 1 expr))
	      (math-poly-degree (nth 2 expr))))
106
	(t 1)))
Eli Zaretskii's avatar
Eli Zaretskii committed
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124

(defun calcFunc-plead (expr var)
  (cond ((eq (car-safe expr) '*)
	 (math-mul (calcFunc-plead (nth 1 expr) var)
		   (calcFunc-plead (nth 2 expr) var)))
	((eq (car-safe expr) '/)
	 (math-div (calcFunc-plead (nth 1 expr) var)
		   (calcFunc-plead (nth 2 expr) var)))
	((and (eq (car-safe expr) '^) (math-natnump (nth 2 expr)))
	 (math-pow (calcFunc-plead (nth 1 expr) var) (nth 2 expr)))
	((Math-primp expr)
	 (if (equal expr var)
	     1
	   expr))
	(t
	 (let ((p (math-is-polynomial expr var)))
	   (if (cdr p)
	       (nth (1- (length p)) p)
125
	     1)))))
Eli Zaretskii's avatar
Eli Zaretskii committed
126 127 128 129 130 131 132 133 134





;;; Polynomial quotient, remainder, and GCD.
;;; Originally by Ove Ewerlid (ewerlid@mizar.DoCS.UU.SE).
;;; Modifications and simplifications by daveg.

135
(defvar math-poly-modulus 1)
Eli Zaretskii's avatar
Eli Zaretskii committed
136 137 138 139 140 141 142 143 144

;;; Return gcd of two polynomials
(defun calcFunc-pgcd (pn pd)
  (if (math-any-floats pn)
      (math-reject-arg pn "Coefficients must be rational"))
  (if (math-any-floats pd)
      (math-reject-arg pd "Coefficients must be rational"))
  (let ((calc-prefer-frac t)
	(math-poly-modulus (math-poly-modulus pn pd)))
145
    (math-poly-gcd pn pd)))
Eli Zaretskii's avatar
Eli Zaretskii committed
146 147

;;; Return only quotient to top of stack (nil if zero)
148

Paul Eggert's avatar
Paul Eggert committed
149
;; calc-poly-div-remainder is a local variable for
150 151 152 153
;; calc-poly-div (in calc-alg.el), but is used by
;; calcFunc-pdiv, which is called by calc-poly-div.
(defvar calc-poly-div-remainder)

Eli Zaretskii's avatar
Eli Zaretskii committed
154 155 156 157 158
(defun calcFunc-pdiv (pn pd &optional base)
  (let* ((calc-prefer-frac t)
	 (math-poly-modulus (math-poly-modulus pn pd))
	 (res (math-poly-div pn pd base)))
    (setq calc-poly-div-remainder (cdr res))
159
    (car res)))
Eli Zaretskii's avatar
Eli Zaretskii committed
160 161 162 163 164

;;; Return only remainder to top of stack
(defun calcFunc-prem (pn pd &optional base)
  (let ((calc-prefer-frac t)
	(math-poly-modulus (math-poly-modulus pn pd)))
165
    (cdr (math-poly-div pn pd base))))
Eli Zaretskii's avatar
Eli Zaretskii committed
166 167 168 169 170

(defun calcFunc-pdivrem (pn pd &optional base)
  (let* ((calc-prefer-frac t)
	 (math-poly-modulus (math-poly-modulus pn pd))
	 (res (math-poly-div pn pd base)))
171
    (list 'vec (car res) (cdr res))))
Eli Zaretskii's avatar
Eli Zaretskii committed
172 173 174 175 176

(defun calcFunc-pdivide (pn pd &optional base)
  (let* ((calc-prefer-frac t)
	 (math-poly-modulus (math-poly-modulus pn pd))
	 (res (math-poly-div pn pd base)))
177
    (math-add (car res) (math-div (cdr res) pd))))
Eli Zaretskii's avatar
Eli Zaretskii committed
178 179 180 181 182 183 184 185 186 187 188 189


;;; Multiply two terms, expanding out products of sums.
(defun math-mul-thru (lhs rhs)
  (if (memq (car-safe lhs) '(+ -))
      (list (car lhs)
	    (math-mul-thru (nth 1 lhs) rhs)
	    (math-mul-thru (nth 2 lhs) rhs))
    (if (memq (car-safe rhs) '(+ -))
	(list (car rhs)
	      (math-mul-thru lhs (nth 1 rhs))
	      (math-mul-thru lhs (nth 2 rhs)))
190
      (math-mul lhs rhs))))
Eli Zaretskii's avatar
Eli Zaretskii committed
191 192 193 194 195 196

(defun math-div-thru (num den)
  (if (memq (car-safe num) '(+ -))
      (list (car num)
	    (math-div-thru (nth 1 num) den)
	    (math-div-thru (nth 2 num) den))
197
    (math-div num den)))
Eli Zaretskii's avatar
Eli Zaretskii committed
198 199 200 201 202 203 204 205


;;; Sort the terms of a sum into canonical order.
(defun math-sort-terms (expr)
  (if (memq (car-safe expr) '(+ -))
      (math-list-to-sum
       (sort (math-sum-to-list expr)
	     (function (lambda (a b) (math-beforep (car a) (car b))))))
206
    expr))
Eli Zaretskii's avatar
Eli Zaretskii committed
207 208 209 210 211 212 213 214

(defun math-list-to-sum (lst)
  (if (cdr lst)
      (list (if (cdr (car lst)) '- '+)
	    (math-list-to-sum (cdr lst))
	    (car (car lst)))
    (if (cdr (car lst))
	(math-neg (car (car lst)))
215
      (car (car lst)))))
Eli Zaretskii's avatar
Eli Zaretskii committed
216 217 218 219 220 221 222 223

(defun math-sum-to-list (tree &optional neg)
  (cond ((eq (car-safe tree) '+)
	 (nconc (math-sum-to-list (nth 1 tree) neg)
		(math-sum-to-list (nth 2 tree) neg)))
	((eq (car-safe tree) '-)
	 (nconc (math-sum-to-list (nth 1 tree) neg)
		(math-sum-to-list (nth 2 tree) (not neg))))
224
	(t (list (cons tree neg)))))
Eli Zaretskii's avatar
Eli Zaretskii committed
225 226 227 228 229

;;; Check if the polynomial coefficients are modulo forms.
(defun math-poly-modulus (expr &optional expr2)
  (or (math-poly-modulus-rec expr)
      (and expr2 (math-poly-modulus-rec expr2))
230
      1))
Eli Zaretskii's avatar
Eli Zaretskii committed
231 232 233 234 235 236

(defun math-poly-modulus-rec (expr)
  (if (and (eq (car-safe expr) 'mod) (Math-natnump (nth 2 expr)))
      (list 'mod 1 (nth 2 expr))
    (and (memq (car-safe expr) '(+ - * /))
	 (or (math-poly-modulus-rec (nth 1 expr))
237
	     (math-poly-modulus-rec (nth 2 expr))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
238 239 240


;;; Divide two polynomials.  Return (quotient . remainder).
241
(defvar math-poly-div-base nil)
Eli Zaretskii's avatar
Eli Zaretskii committed
242 243 244
(defun math-poly-div (u v &optional math-poly-div-base)
  (if math-poly-div-base
      (math-do-poly-div u v)
245
    (math-do-poly-div (calcFunc-expand u) (calcFunc-expand v))))
Eli Zaretskii's avatar
Eli Zaretskii committed
246 247 248 249 250

(defun math-poly-div-exact (u v &optional base)
  (let ((res (math-poly-div u v base)))
    (if (eq (cdr res) 0)
	(car res)
251
      (math-reject-arg (list 'vec u v) "Argument is not a polynomial"))))
Eli Zaretskii's avatar
Eli Zaretskii committed
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280

(defun math-do-poly-div (u v)
  (cond ((math-constp u)
	 (if (math-constp v)
	     (cons (math-div u v) 0)
	   (cons 0 u)))
	((math-constp v)
	 (cons (if (eq v 1)
		   u
		 (if (memq (car-safe u) '(+ -))
		     (math-add-or-sub (math-poly-div-exact (nth 1 u) v)
				      (math-poly-div-exact (nth 2 u) v)
				      nil (eq (car u) '-))
		   (math-div u v)))
	       0))
	((Math-equal u v)
	 (cons math-poly-modulus 0))
	((and (math-atomic-factorp u) (math-atomic-factorp v))
	 (cons (math-simplify (math-div u v)) 0))
	(t
	 (let ((base (or math-poly-div-base
			 (math-poly-div-base u v)))
	       vp up res)
	   (if (or (null base)
		   (null (setq vp (math-is-polynomial v base nil 'gen))))
	       (cons 0 u)
	     (setq up (math-is-polynomial u base nil 'gen)
		   res (math-poly-div-coefs up vp))
	     (cons (math-build-polynomial-expr (car res) base)
281
		   (math-build-polynomial-expr (cdr res) base)))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308

(defun math-poly-div-rec (u v)
  (cond ((math-constp u)
	 (math-div u v))
	((math-constp v)
	 (if (eq v 1)
	     u
	   (if (memq (car-safe u) '(+ -))
	       (math-add-or-sub (math-poly-div-rec (nth 1 u) v)
				(math-poly-div-rec (nth 2 u) v)
				nil (eq (car u) '-))
	     (math-div u v))))
	((Math-equal u v) math-poly-modulus)
	((and (math-atomic-factorp u) (math-atomic-factorp v))
	 (math-simplify (math-div u v)))
	(math-poly-div-base
	 (math-div u v))
	(t
	 (let ((base (math-poly-div-base u v))
	       vp up res)
	   (if (or (null base)
		   (null (setq vp (math-is-polynomial v base nil 'gen))))
	       (math-div u v)
	     (setq up (math-is-polynomial u base nil 'gen)
		   res (math-poly-div-coefs up vp))
	     (math-add (math-build-polynomial-expr (car res) base)
		       (math-div (math-build-polynomial-expr (cdr res) base)
309
				 v)))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334

;;; Divide two polynomials in coefficient-list form.  Return (quot . rem).
(defun math-poly-div-coefs (u v)
  (cond ((null v) (math-reject-arg nil "Division by zero"))
	((< (length u) (length v)) (cons nil u))
	((cdr u)
	 (let ((q nil)
	       (urev (reverse u))
	       (vrev (reverse v)))
	   (while
	       (let ((qk (math-poly-div-rec (math-simplify (car urev))
					    (car vrev)))
		     (up urev)
		     (vp vrev))
		 (if (or q (not (math-zerop qk)))
		     (setq q (cons qk q)))
		 (while (setq up (cdr up) vp (cdr vp))
		   (setcar up (math-sub (car up) (math-mul-thru qk (car vp)))))
		 (setq urev (cdr urev))
		 up))
	   (while (and urev (Math-zerop (car urev)))
	     (setq urev (cdr urev)))
	   (cons q (nreverse (mapcar 'math-simplify urev)))))
	(t
	 (cons (list (math-poly-div-rec (car u) (car v)))
335
	       nil))))
Eli Zaretskii's avatar
Eli Zaretskii committed
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359

;;; Perform a pseudo-division of polynomials.  (See Knuth section 4.6.1.)
;;; This returns only the remainder from the pseudo-division.
(defun math-poly-pseudo-div (u v)
  (cond ((null v) nil)
	((< (length u) (length v)) u)
	((or (cdr u) (cdr v))
	 (let ((urev (reverse u))
	       (vrev (reverse v))
	       up)
	   (while
	       (let ((vp vrev))
		 (setq up urev)
		 (while (setq up (cdr up) vp (cdr vp))
		   (setcar up (math-sub (math-mul-thru (car vrev) (car up))
					(math-mul-thru (car urev) (car vp)))))
		 (setq urev (cdr urev))
		 up)
	     (while up
	       (setcar up (math-mul-thru (car vrev) (car up)))
	       (setq up (cdr up))))
	   (while (and urev (Math-zerop (car urev)))
	     (setq urev (cdr urev)))
	   (nreverse (mapcar 'math-simplify urev))))
360
	(t nil)))
Eli Zaretskii's avatar
Eli Zaretskii committed
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381

;;; Compute the GCD of two multivariate polynomials.
(defun math-poly-gcd (u v)
  (cond ((Math-equal u v) u)
	((math-constp u)
	 (if (Math-zerop u)
	     v
	   (calcFunc-gcd u (calcFunc-pcont v))))
	((math-constp v)
	 (if (Math-zerop v)
	     v
	   (calcFunc-gcd v (calcFunc-pcont u))))
	(t
	 (let ((base (math-poly-gcd-base u v)))
	   (if base
	       (math-simplify
		(calcFunc-expand
		 (math-build-polynomial-expr
		  (math-poly-gcd-coefs (math-is-polynomial u base nil 'gen)
				       (math-is-polynomial v base nil 'gen))
		  base)))
382
	     (calcFunc-gcd (calcFunc-pcont u) (calcFunc-pcont u)))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
383 384 385 386 387 388

(defun math-poly-div-list (lst a)
  (if (eq a 1)
      lst
    (if (eq a -1)
	(math-mul-list lst a)
389
      (mapcar (function (lambda (x) (math-poly-div-exact x a))) lst))))
Eli Zaretskii's avatar
Eli Zaretskii committed
390 391 392 393 394 395 396

(defun math-mul-list (lst a)
  (if (eq a 1)
      lst
    (if (eq a -1)
	(mapcar 'math-neg lst)
      (and (not (eq a 0))
397
	   (mapcar (function (lambda (x) (math-mul x a))) lst)))))
Eli Zaretskii's avatar
Eli Zaretskii committed
398 399 400 401 402 403 404 405 406 407

;;; Run GCD on all elements in a list.
(defun math-poly-gcd-list (lst)
  (if (or (memq 1 lst) (memq -1 lst))
      (math-poly-gcd-frac-list lst)
    (let ((gcd (car lst)))
      (while (and (setq lst (cdr lst)) (not (eq gcd 1)))
	(or (eq (car lst) 0)
	    (setq gcd (math-poly-gcd gcd (car lst)))))
      (if lst (setq lst (math-poly-gcd-frac-list lst)))
408
      gcd)))
Eli Zaretskii's avatar
Eli Zaretskii committed
409 410 411 412 413 414 415 416 417 418

(defun math-poly-gcd-frac-list (lst)
  (while (and lst (not (eq (car-safe (car lst)) 'frac)))
    (setq lst (cdr lst)))
  (if lst
      (let ((denom (nth 2 (car lst))))
	(while (setq lst (cdr lst))
	  (if (eq (car-safe (car lst)) 'frac)
	      (setq denom (calcFunc-lcm denom (nth 2 (car lst))))))
	(list 'frac 1 denom))
419
    1))
Eli Zaretskii's avatar
Eli Zaretskii committed
420

Paul Eggert's avatar
Paul Eggert committed
421
;;; Compute the GCD of two univariate polynomial lists.
Eli Zaretskii's avatar
Eli Zaretskii committed
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
;;; Knuth section 4.6.1, algorithm C.
(defun math-poly-gcd-coefs (u v)
  (let ((d (math-poly-gcd (math-poly-gcd-list u)
			  (math-poly-gcd-list v)))
	(g 1) (h 1) (z 0) hh r delta ghd)
    (while (and u v (Math-zerop (car u)) (Math-zerop (car v)))
      (setq u (cdr u) v (cdr v) z (1+ z)))
    (or (eq d 1)
	(setq u (math-poly-div-list u d)
	      v (math-poly-div-list v d)))
    (while (progn
	     (setq delta (- (length u) (length v)))
	     (if (< delta 0)
		 (setq r u u v v r delta (- delta)))
	     (setq r (math-poly-pseudo-div u v))
	     (cdr r))
      (setq u v
	    v (math-poly-div-list r (math-mul g (math-pow h delta)))
	    g (nth (1- (length u)) u)
	    h (if (<= delta 1)
		  (math-mul (math-pow g delta) (math-pow h (- 1 delta)))
		(math-poly-div-exact (math-pow g delta)
				     (math-pow h (1- delta))))))
    (setq v (if r
		(list d)
	      (math-mul-list (math-poly-div-list v (math-poly-gcd-list v)) d)))
    (if (math-guess-if-neg (nth (1- (length v)) v))
	(setq v (math-mul-list v -1)))
    (while (>= (setq z (1- z)) 0)
      (setq v (cons 0 v)))
452
    v))
Eli Zaretskii's avatar
Eli Zaretskii committed
453 454 455 456 457 458 459 460 461 462 463


;;; Return true if is a factor containing no sums or quotients.
(defun math-atomic-factorp (expr)
  (cond ((eq (car-safe expr) '*)
	 (and (math-atomic-factorp (nth 1 expr))
	      (math-atomic-factorp (nth 2 expr))))
	((memq (car-safe expr) '(+ - /))
	 nil)
	((memq (car-safe expr) '(^ neg))
	 (math-atomic-factorp (nth 1 expr)))
464
	(t t)))
Eli Zaretskii's avatar
Eli Zaretskii committed
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482

;;; Find a suitable base for dividing a by b.
;;; The base must exist in both expressions.
;;; The degree in the numerator must be higher or equal than the
;;; degree in the denominator.
;;; If the above conditions are not met the quotient is just a remainder.
;;; Return nil if this is the case.

(defun math-poly-div-base (a b)
  (let (a-base b-base)
    (and (setq a-base (math-total-polynomial-base a))
	 (setq b-base (math-total-polynomial-base b))
	 (catch 'return
	   (while a-base
	     (let ((maybe (assoc (car (car a-base)) b-base)))
	       (if maybe
		   (if (>= (nth 1 (car a-base)) (nth 1 maybe))
		       (throw 'return (car (car a-base))))))
483
	     (setq a-base (cdr a-base)))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501

;;; Same as above but for gcd algorithm.
;;; Here there is no requirement that degree(a) > degree(b).
;;; Take the base that has the highest degree considering both a and b.
;;; ("a^20+b^21+x^3+a+b", "a+b^2+x^5+a^22+b^10") --> (a 22)

(defun math-poly-gcd-base (a b)
  (let (a-base b-base)
    (and (setq a-base (math-total-polynomial-base a))
	 (setq b-base (math-total-polynomial-base b))
	 (catch 'return
	   (while (and a-base b-base)
	     (if (> (nth 1 (car a-base)) (nth 1 (car b-base)))
		 (if (assoc (car (car a-base)) b-base)
		     (throw 'return (car (car a-base)))
		   (setq a-base (cdr a-base)))
	       (if (assoc (car (car b-base)) a-base)
		   (throw 'return (car (car b-base)))
502
		 (setq b-base (cdr b-base)))))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
503 504 505 506 507 508

;;; Sort a list of polynomial bases.
(defun math-sort-poly-base-list (lst)
  (sort lst (function (lambda (a b)
			(or (> (nth 1 a) (nth 1 b))
			    (and (= (nth 1 a) (nth 1 b))
509
				 (math-beforep (car a) (car b))))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
510 511 512

;;; Given an expression find all variables that are polynomial bases.
;;; Return list in the form '( (var1 degree1) (var2 degree2) ... ).
513

Paul Eggert's avatar
Paul Eggert committed
514
;; The variable math-poly-base-total-base is local to
515 516 517 518
;; math-total-polynomial-base, but is used by math-polynomial-p1,
;; which is called by math-total-polynomial-base.
(defvar math-poly-base-total-base)

Eli Zaretskii's avatar
Eli Zaretskii committed
519
(defun math-total-polynomial-base (expr)
520 521 522
  (let ((math-poly-base-total-base nil)
        (math-poly-base-top-expr expr))
    (math-polynomial-base expr #'math-polynomial-p1)
523 524 525 526 527 528
    (math-sort-poly-base-list math-poly-base-total-base)))

;; The variable math-poly-base-top-expr is local to math-polynomial-base
;; in calc-alg.el, but is used by math-polynomial-p1 which is called
;; by math-polynomial-base.
(defvar math-poly-base-top-expr)
Eli Zaretskii's avatar
Eli Zaretskii committed
529 530

(defun math-polynomial-p1 (subexpr)
531
  (or (assoc subexpr math-poly-base-total-base)
Eli Zaretskii's avatar
Eli Zaretskii committed
532 533 534
      (memq (car subexpr) '(+ - * / neg))
      (and (eq (car subexpr) '^) (natnump (nth 2 subexpr)))
      (let* ((math-poly-base-variable subexpr)
535
	     (exponent (math-polynomial-p math-poly-base-top-expr subexpr)))
Eli Zaretskii's avatar
Eli Zaretskii committed
536
	(if exponent
537 538
	    (setq math-poly-base-total-base (cons (list subexpr exponent)
				       math-poly-base-total-base)))))
539
  nil)
Eli Zaretskii's avatar
Eli Zaretskii committed
540

541
;; The variable math-factored-vars is local to calcFunc-factors and
Paul Eggert's avatar
Paul Eggert committed
542
;; calcFunc-factor, but is used by math-factor-expr and
543 544 545
;; math-factor-expr-part, which are called (directly and indirectly) by
;; calcFunc-factor and calcFunc-factors.
(defvar math-factored-vars)
Eli Zaretskii's avatar
Eli Zaretskii committed
546

547
;; The variable math-fact-expr is local to calcFunc-factors,
Paul Eggert's avatar
Paul Eggert committed
548
;; calcFunc-factor and math-factor-expr, but is used by math-factor-expr-try
549 550 551
;; and math-factor-expr-part, which are called (directly and indirectly) by
;; calcFunc-factor, calcFunc-factors and math-factor-expr.
(defvar math-fact-expr)
Eli Zaretskii's avatar
Eli Zaretskii committed
552

Paul Eggert's avatar
Paul Eggert committed
553 554
;; The variable math-to-list is local to calcFunc-factors and
;; calcFunc-factor, but is used by math-accum-factors, which is
555 556
;; called (indirectly) by calcFunc-factors and calcFunc-factor.
(defvar math-to-list)
Eli Zaretskii's avatar
Eli Zaretskii committed
557

558
(defun calcFunc-factors (math-fact-expr &optional var)
Eli Zaretskii's avatar
Eli Zaretskii committed
559 560 561 562
  (let ((math-factored-vars (if var t nil))
	(math-to-list t)
	(calc-prefer-frac t))
    (or var
563
	(setq var (math-polynomial-base math-fact-expr)))
Eli Zaretskii's avatar
Eli Zaretskii committed
564 565
    (let ((res (math-factor-finish
		(or (catch 'factor (math-factor-expr-try var))
566
		    math-fact-expr))))
Eli Zaretskii's avatar
Eli Zaretskii committed
567 568
      (math-simplify (if (math-vectorp res)
			 res
569
		       (list 'vec (list 'vec res 1)))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
570

571
(defun calcFunc-factor (math-fact-expr &optional var)
Eli Zaretskii's avatar
Eli Zaretskii committed
572 573 574 575 576 577
  (let ((math-factored-vars nil)
	(math-to-list nil)
	(calc-prefer-frac t))
    (math-simplify (math-factor-finish
		    (if var
			(let ((math-factored-vars t))
578 579
			  (or (catch 'factor (math-factor-expr-try var)) math-fact-expr))
		      (math-factor-expr math-fact-expr))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
580 581 582 583 584 585

(defun math-factor-finish (x)
  (if (Math-primp x)
      x
    (if (eq (car x) 'calcFunc-Fac-Prot)
	(math-factor-finish (nth 1 x))
586
      (cons (car x) (mapcar 'math-factor-finish (cdr x))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
587 588 589 590

(defun math-factor-protect (x)
  (if (memq (car-safe x) '(+ -))
      (list 'calcFunc-Fac-Prot x)
591
    x))
Eli Zaretskii's avatar
Eli Zaretskii committed
592

593 594 595 596 597 598
(defun math-factor-expr (math-fact-expr)
  (cond ((eq math-factored-vars t) math-fact-expr)
	((or (memq (car-safe math-fact-expr) '(* / ^ neg))
	     (assq (car-safe math-fact-expr) calc-tweak-eqn-table))
	 (cons (car math-fact-expr) (mapcar 'math-factor-expr (cdr math-fact-expr))))
	((memq (car-safe math-fact-expr) '(+ -))
Eli Zaretskii's avatar
Eli Zaretskii committed
599
	 (let* ((math-factored-vars math-factored-vars)
600
		(y (catch 'factor (math-factor-expr-part math-fact-expr))))
Eli Zaretskii's avatar
Eli Zaretskii committed
601 602
	   (if y
	       (math-factor-expr y)
603 604
	     math-fact-expr)))
	(t math-fact-expr)))
Eli Zaretskii's avatar
Eli Zaretskii committed
605 606 607 608 609 610 611

(defun math-factor-expr-part (x)    ; uses "expr"
  (if (memq (car-safe x) '(+ - * / ^ neg))
      (while (setq x (cdr x))
	(math-factor-expr-part (car x)))
    (and (not (Math-objvecp x))
	 (not (assoc x math-factored-vars))
612
	 (> (math-factor-contains math-fact-expr x) 1)
Eli Zaretskii's avatar
Eli Zaretskii committed
613
	 (setq math-factored-vars (cons (list x) math-factored-vars))
614
	 (math-factor-expr-try x))))
Eli Zaretskii's avatar
Eli Zaretskii committed
615

616 617 618 619 620 621 622 623 624 625
;; The variable math-fet-x is local to math-factor-expr-try, but is
;; used by math-factor-poly-coefs, which is called by math-factor-expr-try.
(defvar math-fet-x)

(defun math-factor-expr-try (math-fet-x)
  (if (eq (car-safe math-fact-expr) '*)
      (let ((res1 (catch 'factor (let ((math-fact-expr (nth 1 math-fact-expr)))
				   (math-factor-expr-try math-fet-x))))
	    (res2 (catch 'factor (let ((math-fact-expr (nth 2 math-fact-expr)))
				   (math-factor-expr-try math-fet-x)))))
Eli Zaretskii's avatar
Eli Zaretskii committed
626
	(and (or res1 res2)
627 628 629 630
	     (throw 'factor (math-accum-factors (or res1 (nth 1 math-fact-expr)) 1
						(or res2 (nth 2 math-fact-expr))))))
    (let* ((p (math-is-polynomial math-fact-expr math-fet-x 30 'gen))
	   (math-poly-modulus (math-poly-modulus math-fact-expr))
Eli Zaretskii's avatar
Eli Zaretskii committed
631 632 633
	   res)
      (and (cdr p)
	   (setq res (math-factor-poly-coefs p))
634
	   (throw 'factor res)))))
Eli Zaretskii's avatar
Eli Zaretskii committed
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664

(defun math-accum-factors (fac pow facs)
  (if math-to-list
      (if (math-vectorp fac)
	  (progn
	    (while (setq fac (cdr fac))
	      (setq facs (math-accum-factors (nth 1 (car fac))
					     (* pow (nth 2 (car fac)))
					     facs)))
	    facs)
	(if (and (eq (car-safe fac) '^) (natnump (nth 2 fac)))
	    (setq pow (* pow (nth 2 fac))
		  fac (nth 1 fac)))
	(if (eq fac 1)
	    facs
	  (or (math-vectorp facs)
	      (setq facs (if (eq facs 1) '(vec)
			   (list 'vec (list 'vec facs 1)))))
	  (let ((found facs))
	    (while (and (setq found (cdr found))
			(not (equal fac (nth 1 (car found))))))
	    (if found
		(progn
		  (setcar (cdr (cdr (car found))) (+ pow (nth 2 (car found))))
		  facs)
	      ;; Put constant term first.
	      (if (and (cdr facs) (Math-ratp (nth 1 (nth 1 facs))))
		  (cons 'vec (cons (nth 1 facs) (cons (list 'vec fac pow)
						      (cdr (cdr facs)))))
		(cons 'vec (cons (list 'vec fac pow) (cdr facs))))))))
665
    (math-mul (math-pow fac pow) (math-factor-protect facs))))
Eli Zaretskii's avatar
Eli Zaretskii committed
666 667

(defun math-factor-poly-coefs (p &optional square-free)    ; uses "x"
668
  (let (t1 t2 temp)
Eli Zaretskii's avatar
Eli Zaretskii committed
669 670 671
    (cond ((not (cdr p))
	   (or (car p) 0))

672
	  ;; Strip off multiples of math-fet-x.
Eli Zaretskii's avatar
Eli Zaretskii committed
673 674 675 676 677 678 679
	  ((Math-zerop (car p))
	   (let ((z 0))
	     (while (and p (Math-zerop (car p)))
	       (setq z (1+ z) p (cdr p)))
	     (if (cdr p)
		 (setq p (math-factor-poly-coefs p square-free))
	       (setq p (math-sort-terms (math-factor-expr (car p)))))
680
	     (math-accum-factors math-fet-x z (math-factor-protect p))))
Eli Zaretskii's avatar
Eli Zaretskii committed
681 682 683 684 685 686 687 688 689 690

	  ;; Factor out content.
	  ((and (not square-free)
		(not (eq 1 (setq t1 (math-mul (math-poly-gcd-list p)
					      (if (math-guess-if-neg
						   (nth (1- (length p)) p))
						  -1 1))))))
	   (math-accum-factors t1 1 (math-factor-poly-coefs
				     (math-poly-div-list p t1) 'cont)))

691
	  ;; Check if linear in math-fet-x.
Eli Zaretskii's avatar
Eli Zaretskii committed
692
	  ((not (cdr (cdr p)))
693 694 695 696 697 698 699
           (math-sort-terms
            (math-add (math-factor-protect
                       (math-sort-terms
                        (math-factor-expr (car p))))
                      (math-mul math-fet-x (math-factor-protect
                                            (math-sort-terms
                                             (math-factor-expr (nth 1 p))))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
700 701 702 703 704 705 706 707 708 709

	  ;; If symbolic coefficients, use FactorRules.
	  ((let ((pp p))
	     (while (and pp (or (Math-ratp (car pp))
				(and (eq (car (car pp)) 'mod)
				     (Math-integerp (nth 1 (car pp)))
				     (Math-integerp (nth 2 (car pp))))))
	       (setq pp (cdr pp)))
	     pp)
	   (let ((res (math-rewrite
710
		       (list 'calcFunc-thecoefs math-fet-x (cons 'vec p))
Eli Zaretskii's avatar
Eli Zaretskii committed
711 712 713 714 715 716 717 718 719
		       '(var FactorRules var-FactorRules))))
	     (or (and (eq (car-safe res) 'calcFunc-thefactors)
		      (= (length res) 3)
		      (math-vectorp (nth 2 res))
		      (let ((facs 1)
			    (vec (nth 2 res)))
			(while (setq vec (cdr vec))
			  (setq facs (math-accum-factors (car vec) 1 facs)))
			facs))
720
		 (math-build-polynomial-expr p math-fet-x))))
Eli Zaretskii's avatar
Eli Zaretskii committed
721 722 723 724 725 726 727 728 729 730 731

	  ;; Check if rational coefficients (i.e., not modulo a prime).
	  ((eq math-poly-modulus 1)

	   ;; Check if there are any squared terms, or a content not = 1.
	   (if (or (eq square-free t)
		   (equal (setq t1 (math-poly-gcd-coefs
				    p (setq t2 (math-poly-deriv-coefs p))))
			  '(1)))

	       ;; We now have a square-free polynomial with integer coefs.
Paul Eggert's avatar
Paul Eggert committed
732
	       ;; For now, we use a kludgy method that finds linear and
Eli Zaretskii's avatar
Eli Zaretskii committed
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
	       ;; quadratic terms using floating-point root-finding.
	       (if (setq t1 (let ((calc-symbolic-mode nil))
			      (math-poly-all-roots nil p t)))
		   (let ((roots (car t1))
			 (csign (if (math-negp (nth (1- (length p)) p)) -1 1))
			 (expr 1)
			 (unfac (nth 1 t1))
			 (scale (nth 2 t1)))
		     (while roots
		       (let ((coef0 (car (car roots)))
			     (coef1 (cdr (car roots))))
			 (setq expr (math-accum-factors
				     (if coef1
					 (let ((den (math-lcm-denoms
						     coef0 coef1)))
					   (setq scale (math-div scale den))
					   (math-add
					    (math-add
751
					     (math-mul den (math-pow math-fet-x 2))
Paul Eggert's avatar
Paul Eggert committed
752
					     (math-mul (math-mul coef1 den)
753
                                                       math-fet-x))
Eli Zaretskii's avatar
Eli Zaretskii committed
754 755 756
					    (math-mul coef0 den)))
				       (let ((den (math-lcm-denoms coef0)))
					 (setq scale (math-div scale den))
757
					 (math-add (math-mul den math-fet-x)
Eli Zaretskii's avatar
Eli Zaretskii committed
758 759 760 761 762 763 764 765
						   (math-mul coef0 den))))
				     1 expr)
			       roots (cdr roots))))
		     (setq expr (math-accum-factors
				 expr 1
				 (math-mul csign
					   (math-build-polynomial-expr
					    (math-mul-list (nth 1 t1) scale)
766 767
					    math-fet-x)))))
		 (math-build-polynomial-expr p math-fet-x))   ; can't factor it.
Eli Zaretskii's avatar
Eli Zaretskii committed
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807

	     ;; Separate out the squared terms (Knuth exercise 4.6.2-34).
	     ;; This step also divides out the content of the polynomial.
	     (let* ((cabs (math-poly-gcd-list p))
		    (csign (if (math-negp (nth (1- (length p)) p)) -1 1))
		    (t1s (math-mul-list t1 csign))
		    (uu nil)
		    (v (car (math-poly-div-coefs p t1s)))
		    (w (car (math-poly-div-coefs t2 t1s))))
	       (while
		   (not (math-poly-zerop
			 (setq t2 (math-poly-simplify
				   (math-poly-mix
				    w 1 (math-poly-deriv-coefs v) -1)))))
		 (setq t1 (math-poly-gcd-coefs v t2)
		       uu (cons t1 uu)
		       v (car (math-poly-div-coefs v t1))
		       w (car (math-poly-div-coefs t2 t1))))
	       (setq t1 (length uu)
		     t2 (math-accum-factors (math-factor-poly-coefs v t)
					    (1+ t1) 1))
	       (while uu
		 (setq t2 (math-accum-factors (math-factor-poly-coefs
					       (car uu) t)
					      t1 t2)
		       t1 (1- t1)
		       uu (cdr uu)))
	       (math-accum-factors (math-mul cabs csign) 1 t2))))

	  ;; Factoring modulo a prime.
	  ((and (= (length (setq temp (math-poly-gcd-coefs
				       p (math-poly-deriv-coefs p))))
		   (length p)))
	   (setq p (car temp))
	   (while (cdr temp)
	     (setq temp (nthcdr (nth 2 math-poly-modulus) temp)
		   p (cons (car temp) p)))
	   (and (setq temp (math-factor-poly-coefs p))
		(math-pow temp (nth 2 math-poly-modulus))))
	  (t
808
	   (math-reject-arg nil "*Modulo factorization not yet implemented")))))
Eli Zaretskii's avatar
Eli Zaretskii committed
809 810 811 812 813 814 815

(defun math-poly-deriv-coefs (p)
  (let ((n 1)
	(dp nil))
    (while (setq p (cdr p))
      (setq dp (cons (math-mul (car p) n) dp)
	    n (1+ n)))
816
    (nreverse dp)))
Eli Zaretskii's avatar
Eli Zaretskii committed
817 818 819 820 821 822 823 824 825 826 827 828

(defun math-factor-contains (x a)
  (if (equal x a)
      1
    (if (memq (car-safe x) '(+ - * / neg))
	(let ((sum 0))
	  (while (setq x (cdr x))
	    (setq sum (+ sum (math-factor-contains (car x) a))))
	  sum)
      (if (and (eq (car-safe x) '^)
	       (natnump (nth 2 x)))
	  (* (math-factor-contains (nth 1 x) a) (nth 2 x))
829
	0))))
Eli Zaretskii's avatar
Eli Zaretskii committed
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851





;;; Merge all quotients and expand/simplify the numerator
(defun calcFunc-nrat (expr)
  (if (math-any-floats expr)
      (setq expr (calcFunc-pfrac expr)))
  (if (or (math-vectorp expr)
	  (assq (car-safe expr) calc-tweak-eqn-table))
      (cons (car expr) (mapcar 'calcFunc-nrat (cdr expr)))
    (let* ((calc-prefer-frac t)
	   (res (math-to-ratpoly expr))
	   (num (math-simplify (math-sort-terms (calcFunc-expand (car res)))))
	   (den (math-simplify (math-sort-terms (calcFunc-expand (cdr res)))))
	   (g (math-poly-gcd num den)))
      (or (eq g 1)
	  (let ((num2 (math-poly-div num g))
		(den2 (math-poly-div den g)))
	    (and (eq (cdr num2) 0) (eq (cdr den2) 0)
		 (setq num (car num2) den (car den2)))))
852
      (math-simplify (math-div num den)))))
Eli Zaretskii's avatar
Eli Zaretskii committed
853 854 855 856

;;; Returns expressions (num . denom).
(defun math-to-ratpoly (expr)
  (let ((res (math-to-ratpoly-rec expr)))
857
    (cons (math-simplify (car res)) (math-simplify (cdr res)))))
Eli Zaretskii's avatar
Eli Zaretskii committed
858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922

(defun math-to-ratpoly-rec (expr)
  (cond ((Math-primp expr)
	 (cons expr 1))
	((memq (car expr) '(+ -))
	 (let ((r1 (math-to-ratpoly-rec (nth 1 expr)))
	       (r2 (math-to-ratpoly-rec (nth 2 expr))))
	   (if (equal (cdr r1) (cdr r2))
	       (cons (list (car expr) (car r1) (car r2)) (cdr r1))
	     (if (eq (cdr r1) 1)
		 (cons (list (car expr)
			     (math-mul (car r1) (cdr r2))
			     (car r2))
		       (cdr r2))
	       (if (eq (cdr r2) 1)
		   (cons (list (car expr)
			       (car r1)
			       (math-mul (car r2) (cdr r1)))
			 (cdr r1))
		 (let ((g (math-poly-gcd (cdr r1) (cdr r2))))
		   (let ((d1 (and (not (eq g 1)) (math-poly-div (cdr r1) g)))
			 (d2 (and (not (eq g 1)) (math-poly-div
						  (math-mul (car r1) (cdr r2))
						  g))))
		     (if (and (eq (cdr d1) 0) (eq (cdr d2) 0))
			 (cons (list (car expr) (car d2)
				     (math-mul (car r2) (car d1)))
			       (math-mul (car d1) (cdr r2)))
		       (cons (list (car expr)
				   (math-mul (car r1) (cdr r2))
				   (math-mul (car r2) (cdr r1)))
			     (math-mul (cdr r1) (cdr r2)))))))))))
	((eq (car expr) '*)
	 (let* ((r1 (math-to-ratpoly-rec (nth 1 expr)))
		(r2 (math-to-ratpoly-rec (nth 2 expr)))
		(g (math-mul (math-poly-gcd (car r1) (cdr r2))
			     (math-poly-gcd (cdr r1) (car r2)))))
	   (if (eq g 1)
	       (cons (math-mul (car r1) (car r2))
		     (math-mul (cdr r1) (cdr r2)))
	     (cons (math-poly-div-exact (math-mul (car r1) (car r2)) g)
		   (math-poly-div-exact (math-mul (cdr r1) (cdr r2)) g)))))
	((eq (car expr) '/)
	 (let* ((r1 (math-to-ratpoly-rec (nth 1 expr)))
		(r2 (math-to-ratpoly-rec (nth 2 expr))))
	   (if (and (eq (cdr r1) 1) (eq (cdr r2) 1))
	       (cons (car r1) (car r2))
	     (let ((g (math-mul (math-poly-gcd (car r1) (car r2))
				(math-poly-gcd (cdr r1) (cdr r2)))))
	       (if (eq g 1)
		   (cons (math-mul (car r1) (cdr r2))
			 (math-mul (cdr r1) (car r2)))
		 (cons (math-poly-div-exact (math-mul (car r1) (cdr r2)) g)
		       (math-poly-div-exact (math-mul (cdr r1) (car r2))
					    g)))))))
	((and (eq (car expr) '^) (integerp (nth 2 expr)))
	 (let ((r1 (math-to-ratpoly-rec (nth 1 expr))))
	   (if (> (nth 2 expr) 0)
	       (cons (math-pow (car r1) (nth 2 expr))
		     (math-pow (cdr r1) (nth 2 expr)))
	     (cons (math-pow (cdr r1) (- (nth 2 expr)))
		   (math-pow (car r1) (- (nth 2 expr)))))))
	((eq (car expr) 'neg)
	 (let ((r1 (math-to-ratpoly-rec (nth 1 expr))))
	   (cons (math-neg (car r1)) (cdr r1))))
923
	(t (cons expr 1))))
Eli Zaretskii's avatar
Eli Zaretskii committed
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951


(defun math-ratpoly-p (expr &optional var)
  (cond ((equal expr var) 1)
	((Math-primp expr) 0)
	((memq (car expr) '(+ -))
	 (let ((p1 (math-ratpoly-p (nth 1 expr) var))
	       p2)
	   (and p1 (setq p2 (math-ratpoly-p (nth 2 expr) var))
		(max p1 p2))))
	((eq (car expr) '*)
	 (let ((p1 (math-ratpoly-p (nth 1 expr) var))
	       p2)
	   (and p1 (setq p2 (math-ratpoly-p (nth 2 expr) var))
		(+ p1 p2))))
	((eq (car expr) 'neg)
	 (math-ratpoly-p (nth 1 expr) var))
	((eq (car expr) '/)
	 (let ((p1 (math-ratpoly-p (nth 1 expr) var))
	       p2)
	   (and p1 (setq p2 (math-ratpoly-p (nth 2 expr) var))
		(- p1 p2))))
	((and (eq (car expr) '^)
	      (integerp (nth 2 expr)))
	 (let ((p1 (math-ratpoly-p (nth 1 expr) var)))
	   (and p1 (* p1 (nth 2 expr)))))
	((not var) 1)
	((math-poly-depends expr var) nil)
952
	(t 0)))
Eli Zaretskii's avatar
Eli Zaretskii committed
953 954 955 956 957 958 959 960 961 962


(defun calcFunc-apart (expr &optional var)
  (cond ((Math-primp expr) expr)
	((eq (car expr) '+)
	 (math-add (calcFunc-apart (nth 1 expr) var)
		   (calcFunc-apart (nth 2 expr) var)))
	((eq (car expr) '-)
	 (math-sub (calcFunc-apart (nth 1 expr) var)
		   (calcFunc-apart (nth 2 expr) var)))
963 964
        ((and var (not (math-ratpoly-p expr var)))
         (math-reject-arg expr "Expected a rational function"))
Eli Zaretskii's avatar
Eli Zaretskii committed
965
	(t
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
         (let* ((calc-prefer-frac t)
                (rat (math-to-ratpoly expr))
                (num (car rat))
                (den (cdr rat)))
           (or var
               (setq var (math-polynomial-base den)))
           (if (not (math-ratpoly-p expr var))
               (math-reject-arg expr "Expected a rational function")
             (let* ((qr (math-poly-div num den))
                    (q (car qr))
                    (r (cdr qr)))
               (math-add q (or (and var
                                    (math-expr-contains den var)
                                    (math-partial-fractions r den var))
                               (math-div r den)))))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
981 982 983


(defun math-padded-polynomial (expr var deg)
David Kastrup's avatar
David Kastrup committed
984 985 986
  "Return a polynomial as list of coefficients.
If EXPR is of the form \"a + bx + cx^2 + ...\" in the variable VAR, return
the list (a b c ...) with at least DEG elements, else return NIL."
Eli Zaretskii's avatar
Eli Zaretskii committed
987
  (let ((p (math-is-polynomial expr var deg)))
988
    (append p (make-list (- deg (length p)) 0))))
Eli Zaretskii's avatar
Eli Zaretskii committed
989 990

(defun math-partial-fractions (r den var)
David Kastrup's avatar
David Kastrup committed
991 992 993
  "Return R divided by DEN expressed in partial fractions of VAR.
All whole factors of DEN have already been split off from R.
If no partial fraction representation can be found, return nil."
Eli Zaretskii's avatar
Eli Zaretskii committed
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
  (let* ((fden (calcFunc-factors den var))
	 (tdeg (math-polynomial-p den var))
	 (fp fden)
	 (dlist nil)
	 (eqns 0)
	 (lz nil)
	 (tz (make-list (1- tdeg) 0))
	 (calc-matrix-mode 'scalar))
    (and (not (and (= (length fden) 2) (eq (nth 2 (nth 1 fden)) 1)))
	 (progn
	   (while (setq fp (cdr fp))
	     (let ((rpt (nth 2 (car fp)))
		   (deg (math-polynomial-p (nth 1 (car fp)) var))
		   dnum dvar deg2)
	       (while (> rpt 0)
		 (setq deg2 deg
		       dnum 0)
		 (while (> deg2 0)
		   (setq dvar (append '(vec) lz '(1) tz)
			 lz (cons 0 lz)
			 tz (cdr tz)
			 deg2 (1- deg2)
			 dnum (math-add dnum (math-mul dvar
						       (math-pow var deg2)))
			 dlist (cons (and (= deg2 (1- deg))
					  (math-pow (nth 1 (car fp)) rpt))
				     dlist)))
		 (let ((fpp fden)
		       (mult 1))
		   (while (setq fpp (cdr fpp))
		     (or (eq fpp fp)
			 (setq mult (math-mul mult
					      (math-pow (nth 1 (car fpp))
							(nth 2 (car fpp)))))))
		   (setq dnum (math-mul dnum mult)))
		 (setq eqns (math-add eqns (math-mul dnum
						     (math-pow
						      (nth 1 (car fp))
						      (- (nth 2 (car fp))
							 rpt))))
		       rpt (1- rpt)))))
	   (setq eqns (math-div (cons 'vec (math-padded-polynomial r var tdeg))
				(math-transpose
				 (cons 'vec
				       (mapcar
					(function
					 (lambda (x)
					   (cons 'vec (math-padded-polynomial
						       x var tdeg))))
					(cdr eqns))))))
	   (and (math-vectorp eqns)
		(let ((res 0)
		      (num nil))
		  (setq eqns (nreverse eqns))
		  (while eqns
		    (setq num (cons (car eqns) num)
			  eqns (cdr eqns))
		    (if (car dlist)
			(setq num (math-build-polynomial-expr
				   (nreverse num) var)
			      res (math-add res (math-div num (car dlist)))
			      num nil))
		    (setq dlist (cdr dlist)))
1057
		  (math-normalize res)))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079



(defun math-expand-term (expr)
  (cond ((and (eq (car-safe expr) '*)
	      (memq (car-safe (nth 1 expr)) '(+ -)))
	 (math-add-or-sub (list '* (nth 1 (nth 1 expr)) (nth 2 expr))
			  (list '* (nth 2 (nth 1 expr)) (nth 2 expr))
			  nil (eq (car (nth 1 expr)) '-)))
	((and (eq (car-safe expr) '*)
	      (memq (car-safe (nth 2 expr)) '(+ -)))
	 (math-add-or-sub (list '* (nth 1 expr) (nth 1 (nth 2 expr)))
			  (list '* (nth 1 expr) (nth 2 (nth 2 expr)))
			  nil (eq (car (nth 2 expr)) '-)))
	((and (eq (car-safe expr) '/)
	      (memq (car-safe (nth 1 expr)) '(+ -)))
	 (math-add-or-sub (list '/ (nth 1 (nth 1 expr)) (nth 2 expr))
			  (list '/ (nth 2 (nth 1 expr)) (nth 2 expr))
			  nil (eq (car (nth 1 expr)) '-)))
	((and (eq (car-safe expr) '^)
	      (memq (car-safe (nth 1 expr)) '(+ -))
	      (integerp (nth 2 expr))
Paul Eggert's avatar
Paul Eggert committed
1080
              (if (and
1081 1082 1083 1084 1085 1086 1087 1088
                   (or (math-known-matrixp (nth 1 (nth 1 expr)))
                       (math-known-matrixp (nth 2 (nth 1 expr)))
                       (and
                        calc-matrix-mode
                        (not (eq calc-matrix-mode 'scalar))
                        (not (and (math-known-scalarp (nth 1 (nth 1 expr)))
                                  (math-known-scalarp (nth 2 (nth 1 expr)))))))
                   (> (nth 2 expr) 1))
1089 1090 1091 1092
                  (if (= (nth 2 expr) 2)
                      (math-add-or-sub (list '* (nth 1 (nth 1 expr)) (nth 1 expr))
                                       (list '* (nth 2 (nth 1 expr)) (nth 1 expr))
                                       nil (eq (car (nth 1 expr)) '-))
Paul Eggert's avatar
Paul Eggert committed
1093 1094
                    (math-add-or-sub (list '* (nth 1 (nth 1 expr))
                                           (list '^ (nth 1 expr)
1095
                                                 (1- (nth 2 expr))))
Paul Eggert's avatar
Paul Eggert committed
1096 1097
                                     (list '* (nth 2 (nth 1 expr))
                                           (list '^ (nth 1 expr)
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
                                                 (1- (nth 2 expr))))
                                     nil (eq (car (nth 1 expr)) '-)))
                (if (> (nth 2 expr) 0)
                    (or (and (or (> math-mt-many 500000) (< math-mt-many -500000))
                             (math-expand-power (nth 1 expr) (nth 2 expr)
                                                nil t))
                        (list '*
                              (nth 1 expr)
                              (list '^ (nth 1 expr) (1- (nth 2 expr)))))
                  (if (< (nth 2 expr) 0)
                      (list '/ 1 (list '^ (nth 1 expr) (- (nth 2 expr)))))))))
1109
	(t expr)))
Eli Zaretskii's avatar
Eli Zaretskii committed
1110 1111

(defun calcFunc-expand (expr &optional many)
1112
  (math-normalize (math-map-tree 'math-expand-term expr many)))
Eli Zaretskii's avatar
Eli Zaretskii committed
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194

(defun math-expand-power (x n &optional var else-nil)
  (or (and (natnump n)
	   (memq (car-safe x) '(+ -))
	   (let ((terms nil)
		 (cterms nil))
	     (while (memq (car-safe x) '(+ -))
	       (setq terms (cons (if (eq (car x) '-)
				     (math-neg (nth 2 x))
				   (nth 2 x))
				 terms)
		     x (nth 1 x)))
	     (setq terms (cons x terms))
	     (if var
		 (let ((p terms))
		   (while p
		     (or (math-expr-contains (car p) var)
			 (setq terms (delq (car p) terms)
			       cterms (cons (car p) cterms)))
		     (setq p (cdr p)))
		   (if cterms
		       (setq terms (cons (apply 'calcFunc-add cterms)
					 terms)))))
	     (if (= (length terms) 2)
		 (let ((i 0)
		       (accum 0))
		   (while (<= i n)
		     (setq accum (list '+ accum
				       (list '* (calcFunc-choose n i)
					     (list '*
						   (list '^ (nth 1 terms) i)
						   (list '^ (car terms)
							 (- n i)))))
			   i (1+ i)))
		   accum)
	       (if (= n 2)
		   (let ((accum 0)
			 (p1 terms)
			 p2)
		     (while p1
		       (setq accum (list '+ accum
					 (list '^ (car p1) 2))
			     p2 p1)
		       (while (setq p2 (cdr p2))
			 (setq accum (list '+ accum
					   (list '* 2 (list '*
							    (car p1)
							    (car p2))))))
		       (setq p1 (cdr p1)))
		     accum)
		 (if (= n 3)
		     (let ((accum 0)
			   (p1 terms)
			   p2 p3)
		       (while p1
			 (setq accum (list '+ accum (list '^ (car p1) 3))
			       p2 p1)
			 (while (setq p2 (cdr p2))
			   (setq accum (list '+
					     (list '+
						   accum
						   (list '* 3
							 (list
							  '*
							  (list '^ (car p1) 2)
							  (car p2))))
					     (list '* 3
						   (list
						    '* (car p1)
						    (list '^ (car p2) 2))))
				 p3 p2)
			   (while (setq p3 (cdr p3))
			     (setq accum (list '+ accum
					       (list '* 6
						     (list '*
							   (car p1)
							   (list
							    '* (car p2)
							    (car p3))))))))
			 (setq p1 (cdr p1)))
		       accum))))))
      (and (not else-nil)
1195
	   (list '^ x n))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1196 1197

(defun calcFunc-expandpow (x n)
1198
  (math-normalize (math-expand-power x n)))
Eli Zaretskii's avatar
Eli Zaretskii committed
1199

Jay Belanger's avatar
Jay Belanger committed
1200 1201
(provide 'calc-poly)

1202
;;; calc-poly.el ends here