3 * This file implements several functions that work on univariate and
4 * multivariate polynomials and rational functions.
5 * These functions include polynomial quotient and remainder, GCD and LCM
6 * computation, square-free factorization and rational function normalization. */
9 * GiNaC Copyright (C) 1999-2003 Johannes Gutenberg University Mainz, Germany
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
34 #include "expairseq.h"
41 #include "relational.h"
42 #include "operators.h"
50 // If comparing expressions (ex::compare()) is fast, you can set this to 1.
51 // Some routines like quo(), rem() and gcd() will then return a quick answer
52 // when they are called with two identical arguments.
53 #define FAST_COMPARE 1
55 // Set this if you want divide_in_z() to use remembering
56 #define USE_REMEMBER 0
58 // Set this if you want divide_in_z() to use trial division followed by
59 // polynomial interpolation (always slower except for completely dense
61 #define USE_TRIAL_DIVISION 0
63 // Set this to enable some statistical output for the GCD routines
68 // Statistics variables
69 static int gcd_called = 0;
70 static int sr_gcd_called = 0;
71 static int heur_gcd_called = 0;
72 static int heur_gcd_failed = 0;
74 // Print statistics at end of program
75 static struct _stat_print {
78 std::cout << "gcd() called " << gcd_called << " times\n";
79 std::cout << "sr_gcd() called " << sr_gcd_called << " times\n";
80 std::cout << "heur_gcd() called " << heur_gcd_called << " times\n";
81 std::cout << "heur_gcd() failed " << heur_gcd_failed << " times\n";
87 /** Return pointer to first symbol found in expression. Due to GiNaCĀ“s
88 * internal ordering of terms, it may not be obvious which symbol this
89 * function returns for a given expression.
91 * @param e expression to search
92 * @param x pointer to first symbol found (returned)
93 * @return "false" if no symbol was found, "true" otherwise */
94 static bool get_first_symbol(const ex &e, const symbol *&x)
96 if (is_a<symbol>(e)) {
97 x = &ex_to<symbol>(e);
99 } else if (is_exactly_a<add>(e) || is_exactly_a<mul>(e)) {
100 for (size_t i=0; i<e.nops(); i++)
101 if (get_first_symbol(e.op(i), x))
103 } else if (is_exactly_a<power>(e)) {
104 if (get_first_symbol(e.op(0), x))
112 * Statistical information about symbols in polynomials
115 /** This structure holds information about the highest and lowest degrees
116 * in which a symbol appears in two multivariate polynomials "a" and "b".
117 * A vector of these structures with information about all symbols in
118 * two polynomials can be created with the function get_symbol_stats().
120 * @see get_symbol_stats */
122 /** Pointer to symbol */
125 /** Highest degree of symbol in polynomial "a" */
128 /** Highest degree of symbol in polynomial "b" */
131 /** Lowest degree of symbol in polynomial "a" */
134 /** Lowest degree of symbol in polynomial "b" */
137 /** Maximum of deg_a and deg_b (Used for sorting) */
140 /** Maximum number of terms of leading coefficient of symbol in both polynomials */
143 /** Commparison operator for sorting */
144 bool operator<(const sym_desc &x) const
146 if (max_deg == x.max_deg)
147 return max_lcnops < x.max_lcnops;
149 return max_deg < x.max_deg;
153 // Vector of sym_desc structures
154 typedef std::vector<sym_desc> sym_desc_vec;
156 // Add symbol the sym_desc_vec (used internally by get_symbol_stats())
157 static void add_symbol(const symbol *s, sym_desc_vec &v)
159 sym_desc_vec::const_iterator it = v.begin(), itend = v.end();
160 while (it != itend) {
161 if (it->sym->compare(*s) == 0) // If it's already in there, don't add it a second time
170 // Collect all symbols of an expression (used internally by get_symbol_stats())
171 static void collect_symbols(const ex &e, sym_desc_vec &v)
173 if (is_a<symbol>(e)) {
174 add_symbol(&ex_to<symbol>(e), v);
175 } else if (is_exactly_a<add>(e) || is_exactly_a<mul>(e)) {
176 for (size_t i=0; i<e.nops(); i++)
177 collect_symbols(e.op(i), v);
178 } else if (is_exactly_a<power>(e)) {
179 collect_symbols(e.op(0), v);
183 /** Collect statistical information about symbols in polynomials.
184 * This function fills in a vector of "sym_desc" structs which contain
185 * information about the highest and lowest degrees of all symbols that
186 * appear in two polynomials. The vector is then sorted by minimum
187 * degree (lowest to highest). The information gathered by this
188 * function is used by the GCD routines to identify trivial factors
189 * and to determine which variable to choose as the main variable
190 * for GCD computation.
192 * @param a first multivariate polynomial
193 * @param b second multivariate polynomial
194 * @param v vector of sym_desc structs (filled in) */
195 static void get_symbol_stats(const ex &a, const ex &b, sym_desc_vec &v)
197 collect_symbols(a.eval(), v); // eval() to expand assigned symbols
198 collect_symbols(b.eval(), v);
199 sym_desc_vec::iterator it = v.begin(), itend = v.end();
200 while (it != itend) {
201 int deg_a = a.degree(*(it->sym));
202 int deg_b = b.degree(*(it->sym));
205 it->max_deg = std::max(deg_a, deg_b);
206 it->max_lcnops = std::max(a.lcoeff(*(it->sym)).nops(), b.lcoeff(*(it->sym)).nops());
207 it->ldeg_a = a.ldegree(*(it->sym));
208 it->ldeg_b = b.ldegree(*(it->sym));
211 std::sort(v.begin(), v.end());
214 std::clog << "Symbols:\n";
215 it = v.begin(); itend = v.end();
216 while (it != itend) {
217 std::clog << " " << *it->sym << ": deg_a=" << it->deg_a << ", deg_b=" << it->deg_b << ", ldeg_a=" << it->ldeg_a << ", ldeg_b=" << it->ldeg_b << ", max_deg=" << it->max_deg << ", max_lcnops=" << it->max_lcnops << endl;
218 std::clog << " lcoeff_a=" << a.lcoeff(*(it->sym)) << ", lcoeff_b=" << b.lcoeff(*(it->sym)) << endl;
226 * Computation of LCM of denominators of coefficients of a polynomial
229 // Compute LCM of denominators of coefficients by going through the
230 // expression recursively (used internally by lcm_of_coefficients_denominators())
231 static numeric lcmcoeff(const ex &e, const numeric &l)
233 if (e.info(info_flags::rational))
234 return lcm(ex_to<numeric>(e).denom(), l);
235 else if (is_exactly_a<add>(e)) {
237 for (size_t i=0; i<e.nops(); i++)
238 c = lcmcoeff(e.op(i), c);
240 } else if (is_exactly_a<mul>(e)) {
242 for (size_t i=0; i<e.nops(); i++)
243 c *= lcmcoeff(e.op(i), _num1);
245 } else if (is_exactly_a<power>(e)) {
246 if (is_a<symbol>(e.op(0)))
249 return pow(lcmcoeff(e.op(0), l), ex_to<numeric>(e.op(1)));
254 /** Compute LCM of denominators of coefficients of a polynomial.
255 * Given a polynomial with rational coefficients, this function computes
256 * the LCM of the denominators of all coefficients. This can be used
257 * to bring a polynomial from Q[X] to Z[X].
259 * @param e multivariate polynomial (need not be expanded)
260 * @return LCM of denominators of coefficients */
261 static numeric lcm_of_coefficients_denominators(const ex &e)
263 return lcmcoeff(e, _num1);
266 /** Bring polynomial from Q[X] to Z[X] by multiplying in the previously
267 * determined LCM of the coefficient's denominators.
269 * @param e multivariate polynomial (need not be expanded)
270 * @param lcm LCM to multiply in */
271 static ex multiply_lcm(const ex &e, const numeric &lcm)
273 if (is_exactly_a<mul>(e)) {
274 size_t num = e.nops();
275 exvector v; v.reserve(num + 1);
276 numeric lcm_accum = _num1;
277 for (size_t i=0; i<num; i++) {
278 numeric op_lcm = lcmcoeff(e.op(i), _num1);
279 v.push_back(multiply_lcm(e.op(i), op_lcm));
282 v.push_back(lcm / lcm_accum);
283 return (new mul(v))->setflag(status_flags::dynallocated);
284 } else if (is_exactly_a<add>(e)) {
285 size_t num = e.nops();
286 exvector v; v.reserve(num);
287 for (size_t i=0; i<num; i++)
288 v.push_back(multiply_lcm(e.op(i), lcm));
289 return (new add(v))->setflag(status_flags::dynallocated);
290 } else if (is_exactly_a<power>(e)) {
291 if (is_a<symbol>(e.op(0)))
294 return pow(multiply_lcm(e.op(0), lcm.power(ex_to<numeric>(e.op(1)).inverse())), e.op(1));
300 /** Compute the integer content (= GCD of all numeric coefficients) of an
301 * expanded polynomial.
303 * @param e expanded polynomial
304 * @return integer content */
305 numeric ex::integer_content(void) const
308 return bp->integer_content();
311 numeric basic::integer_content(void) const
316 numeric numeric::integer_content(void) const
321 numeric add::integer_content(void) const
323 epvector::const_iterator it = seq.begin();
324 epvector::const_iterator itend = seq.end();
326 while (it != itend) {
327 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
328 GINAC_ASSERT(is_exactly_a<numeric>(it->coeff));
329 c = gcd(ex_to<numeric>(it->coeff), c);
332 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
333 c = gcd(ex_to<numeric>(overall_coeff),c);
337 numeric mul::integer_content(void) const
339 #ifdef DO_GINAC_ASSERT
340 epvector::const_iterator it = seq.begin();
341 epvector::const_iterator itend = seq.end();
342 while (it != itend) {
343 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
346 #endif // def DO_GINAC_ASSERT
347 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
348 return abs(ex_to<numeric>(overall_coeff));
353 * Polynomial quotients and remainders
356 /** Quotient q(x) of polynomials a(x) and b(x) in Q[x].
357 * It satisfies a(x)=b(x)*q(x)+r(x).
359 * @param a first polynomial in x (dividend)
360 * @param b second polynomial in x (divisor)
361 * @param x a and b are polynomials in x
362 * @param check_args check whether a and b are polynomials with rational
363 * coefficients (defaults to "true")
364 * @return quotient of a and b in Q[x] */
365 ex quo(const ex &a, const ex &b, const symbol &x, bool check_args)
368 throw(std::overflow_error("quo: division by zero"));
369 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b))
375 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
376 throw(std::invalid_argument("quo: arguments must be polynomials over the rationals"));
378 // Polynomial long division
382 int bdeg = b.degree(x);
383 int rdeg = r.degree(x);
384 ex blcoeff = b.expand().coeff(x, bdeg);
385 bool blcoeff_is_numeric = is_exactly_a<numeric>(blcoeff);
386 exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
387 while (rdeg >= bdeg) {
388 ex term, rcoeff = r.coeff(x, rdeg);
389 if (blcoeff_is_numeric)
390 term = rcoeff / blcoeff;
392 if (!divide(rcoeff, blcoeff, term, false))
393 return (new fail())->setflag(status_flags::dynallocated);
395 term *= power(x, rdeg - bdeg);
397 r -= (term * b).expand();
402 return (new add(v))->setflag(status_flags::dynallocated);
406 /** Remainder r(x) of polynomials a(x) and b(x) in Q[x].
407 * It satisfies a(x)=b(x)*q(x)+r(x).
409 * @param a first polynomial in x (dividend)
410 * @param b second polynomial in x (divisor)
411 * @param x a and b are polynomials in x
412 * @param check_args check whether a and b are polynomials with rational
413 * coefficients (defaults to "true")
414 * @return remainder of a(x) and b(x) in Q[x] */
415 ex rem(const ex &a, const ex &b, const symbol &x, bool check_args)
418 throw(std::overflow_error("rem: division by zero"));
419 if (is_exactly_a<numeric>(a)) {
420 if (is_exactly_a<numeric>(b))
429 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
430 throw(std::invalid_argument("rem: arguments must be polynomials over the rationals"));
432 // Polynomial long division
436 int bdeg = b.degree(x);
437 int rdeg = r.degree(x);
438 ex blcoeff = b.expand().coeff(x, bdeg);
439 bool blcoeff_is_numeric = is_exactly_a<numeric>(blcoeff);
440 while (rdeg >= bdeg) {
441 ex term, rcoeff = r.coeff(x, rdeg);
442 if (blcoeff_is_numeric)
443 term = rcoeff / blcoeff;
445 if (!divide(rcoeff, blcoeff, term, false))
446 return (new fail())->setflag(status_flags::dynallocated);
448 term *= power(x, rdeg - bdeg);
449 r -= (term * b).expand();
458 /** Decompose rational function a(x)=N(x)/D(x) into P(x)+n(x)/D(x)
459 * with degree(n, x) < degree(D, x).
461 * @param a rational function in x
462 * @param x a is a function of x
463 * @return decomposed function. */
464 ex decomp_rational(const ex &a, const symbol &x)
466 ex nd = numer_denom(a);
467 ex numer = nd.op(0), denom = nd.op(1);
468 ex q = quo(numer, denom, x);
469 if (is_exactly_a<fail>(q))
472 return q + rem(numer, denom, x) / denom;
476 /** Pseudo-remainder of polynomials a(x) and b(x) in Q[x].
478 * @param a first polynomial in x (dividend)
479 * @param b second polynomial in x (divisor)
480 * @param x a and b are polynomials in x
481 * @param check_args check whether a and b are polynomials with rational
482 * coefficients (defaults to "true")
483 * @return pseudo-remainder of a(x) and b(x) in Q[x] */
484 ex prem(const ex &a, const ex &b, const symbol &x, bool check_args)
487 throw(std::overflow_error("prem: division by zero"));
488 if (is_exactly_a<numeric>(a)) {
489 if (is_exactly_a<numeric>(b))
494 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
495 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
497 // Polynomial long division
500 int rdeg = r.degree(x);
501 int bdeg = eb.degree(x);
504 blcoeff = eb.coeff(x, bdeg);
508 eb -= blcoeff * power(x, bdeg);
512 int delta = rdeg - bdeg + 1, i = 0;
513 while (rdeg >= bdeg && !r.is_zero()) {
514 ex rlcoeff = r.coeff(x, rdeg);
515 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
519 r -= rlcoeff * power(x, rdeg);
520 r = (blcoeff * r).expand() - term;
524 return power(blcoeff, delta - i) * r;
528 /** Sparse pseudo-remainder of polynomials a(x) and b(x) in Q[x].
530 * @param a first polynomial in x (dividend)
531 * @param b second polynomial in x (divisor)
532 * @param x a and b are polynomials in x
533 * @param check_args check whether a and b are polynomials with rational
534 * coefficients (defaults to "true")
535 * @return sparse pseudo-remainder of a(x) and b(x) in Q[x] */
536 ex sprem(const ex &a, const ex &b, const symbol &x, bool check_args)
539 throw(std::overflow_error("prem: division by zero"));
540 if (is_exactly_a<numeric>(a)) {
541 if (is_exactly_a<numeric>(b))
546 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
547 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
549 // Polynomial long division
552 int rdeg = r.degree(x);
553 int bdeg = eb.degree(x);
556 blcoeff = eb.coeff(x, bdeg);
560 eb -= blcoeff * power(x, bdeg);
564 while (rdeg >= bdeg && !r.is_zero()) {
565 ex rlcoeff = r.coeff(x, rdeg);
566 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
570 r -= rlcoeff * power(x, rdeg);
571 r = (blcoeff * r).expand() - term;
578 /** Exact polynomial division of a(X) by b(X) in Q[X].
580 * @param a first multivariate polynomial (dividend)
581 * @param b second multivariate polynomial (divisor)
582 * @param q quotient (returned)
583 * @param check_args check whether a and b are polynomials with rational
584 * coefficients (defaults to "true")
585 * @return "true" when exact division succeeds (quotient returned in q),
586 * "false" otherwise (q left untouched) */
587 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
590 throw(std::overflow_error("divide: division by zero"));
595 if (is_exactly_a<numeric>(b)) {
598 } else if (is_exactly_a<numeric>(a))
606 if (check_args && (!a.info(info_flags::rational_polynomial) ||
607 !b.info(info_flags::rational_polynomial)))
608 throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
612 if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
613 throw(std::invalid_argument("invalid expression in divide()"));
615 // Polynomial long division (recursive)
621 int bdeg = b.degree(*x);
622 int rdeg = r.degree(*x);
623 ex blcoeff = b.expand().coeff(*x, bdeg);
624 bool blcoeff_is_numeric = is_exactly_a<numeric>(blcoeff);
625 exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
626 while (rdeg >= bdeg) {
627 ex term, rcoeff = r.coeff(*x, rdeg);
628 if (blcoeff_is_numeric)
629 term = rcoeff / blcoeff;
631 if (!divide(rcoeff, blcoeff, term, false))
633 term *= power(*x, rdeg - bdeg);
635 r -= (term * b).expand();
637 q = (new add(v))->setflag(status_flags::dynallocated);
651 typedef std::pair<ex, ex> ex2;
652 typedef std::pair<ex, bool> exbool;
655 bool operator() (const ex2 &p, const ex2 &q) const
657 int cmp = p.first.compare(q.first);
658 return ((cmp<0) || (!(cmp>0) && p.second.compare(q.second)<0));
662 typedef std::map<ex2, exbool, ex2_less> ex2_exbool_remember;
666 /** Exact polynomial division of a(X) by b(X) in Z[X].
667 * This functions works like divide() but the input and output polynomials are
668 * in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
669 * divide(), it doesnĀ“t check whether the input polynomials really are integer
670 * polynomials, so be careful of what you pass in. Also, you have to run
671 * get_symbol_stats() over the input polynomials before calling this function
672 * and pass an iterator to the first element of the sym_desc vector. This
673 * function is used internally by the heur_gcd().
675 * @param a first multivariate polynomial (dividend)
676 * @param b second multivariate polynomial (divisor)
677 * @param q quotient (returned)
678 * @param var iterator to first element of vector of sym_desc structs
679 * @return "true" when exact division succeeds (the quotient is returned in
680 * q), "false" otherwise.
681 * @see get_symbol_stats, heur_gcd */
682 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
686 throw(std::overflow_error("divide_in_z: division by zero"));
687 if (b.is_equal(_ex1)) {
691 if (is_exactly_a<numeric>(a)) {
692 if (is_exactly_a<numeric>(b)) {
694 return q.info(info_flags::integer);
707 static ex2_exbool_remember dr_remember;
708 ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
709 if (remembered != dr_remember.end()) {
710 q = remembered->second.first;
711 return remembered->second.second;
716 const symbol *x = var->sym;
719 int adeg = a.degree(*x), bdeg = b.degree(*x);
723 #if USE_TRIAL_DIVISION
725 // Trial division with polynomial interpolation
728 // Compute values at evaluation points 0..adeg
729 vector<numeric> alpha; alpha.reserve(adeg + 1);
730 exvector u; u.reserve(adeg + 1);
731 numeric point = _num0;
733 for (i=0; i<=adeg; i++) {
734 ex bs = b.subs(*x == point);
735 while (bs.is_zero()) {
737 bs = b.subs(*x == point);
739 if (!divide_in_z(a.subs(*x == point), bs, c, var+1))
741 alpha.push_back(point);
747 vector<numeric> rcp; rcp.reserve(adeg + 1);
748 rcp.push_back(_num0);
749 for (k=1; k<=adeg; k++) {
750 numeric product = alpha[k] - alpha[0];
752 product *= alpha[k] - alpha[i];
753 rcp.push_back(product.inverse());
756 // Compute Newton coefficients
757 exvector v; v.reserve(adeg + 1);
759 for (k=1; k<=adeg; k++) {
761 for (i=k-2; i>=0; i--)
762 temp = temp * (alpha[k] - alpha[i]) + v[i];
763 v.push_back((u[k] - temp) * rcp[k]);
766 // Convert from Newton form to standard form
768 for (k=adeg-1; k>=0; k--)
769 c = c * (*x - alpha[k]) + v[k];
771 if (c.degree(*x) == (adeg - bdeg)) {
779 // Polynomial long division (recursive)
785 ex blcoeff = eb.coeff(*x, bdeg);
786 exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
787 while (rdeg >= bdeg) {
788 ex term, rcoeff = r.coeff(*x, rdeg);
789 if (!divide_in_z(rcoeff, blcoeff, term, var+1))
791 term = (term * power(*x, rdeg - bdeg)).expand();
793 r -= (term * eb).expand();
795 q = (new add(v))->setflag(status_flags::dynallocated);
797 dr_remember[ex2(a, b)] = exbool(q, true);
804 dr_remember[ex2(a, b)] = exbool(q, false);
813 * Separation of unit part, content part and primitive part of polynomials
816 /** Compute unit part (= sign of leading coefficient) of a multivariate
817 * polynomial in Z[x]. The product of unit part, content part, and primitive
818 * part is the polynomial itself.
820 * @param x variable in which to compute the unit part
822 * @see ex::content, ex::primpart */
823 ex ex::unit(const symbol &x) const
825 ex c = expand().lcoeff(x);
826 if (is_exactly_a<numeric>(c))
827 return c < _ex0 ? _ex_1 : _ex1;
830 if (get_first_symbol(c, y))
833 throw(std::invalid_argument("invalid expression in unit()"));
838 /** Compute content part (= unit normal GCD of all coefficients) of a
839 * multivariate polynomial in Z[x]. The product of unit part, content part,
840 * and primitive part is the polynomial itself.
842 * @param x variable in which to compute the content part
843 * @return content part
844 * @see ex::unit, ex::primpart */
845 ex ex::content(const symbol &x) const
849 if (is_exactly_a<numeric>(*this))
850 return info(info_flags::negative) ? -*this : *this;
855 // First, try the integer content
856 ex c = e.integer_content();
858 ex lcoeff = r.lcoeff(x);
859 if (lcoeff.info(info_flags::integer))
862 // GCD of all coefficients
863 int deg = e.degree(x);
864 int ldeg = e.ldegree(x);
866 return e.lcoeff(x) / e.unit(x);
868 for (int i=ldeg; i<=deg; i++)
869 c = gcd(e.coeff(x, i), c, NULL, NULL, false);
874 /** Compute primitive part of a multivariate polynomial in Z[x].
875 * The product of unit part, content part, and primitive part is the
878 * @param x variable in which to compute the primitive part
879 * @return primitive part
880 * @see ex::unit, ex::content */
881 ex ex::primpart(const symbol &x) const
885 if (is_exactly_a<numeric>(*this))
892 if (is_exactly_a<numeric>(c))
893 return *this / (c * u);
895 return quo(*this, c * u, x, false);
899 /** Compute primitive part of a multivariate polynomial in Z[x] when the
900 * content part is already known. This function is faster in computing the
901 * primitive part than the previous function.
903 * @param x variable in which to compute the primitive part
904 * @param c previously computed content part
905 * @return primitive part */
906 ex ex::primpart(const symbol &x, const ex &c) const
912 if (is_exactly_a<numeric>(*this))
916 if (is_exactly_a<numeric>(c))
917 return *this / (c * u);
919 return quo(*this, c * u, x, false);
924 * GCD of multivariate polynomials
927 /** Compute GCD of multivariate polynomials using the subresultant PRS
928 * algorithm. This function is used internally by gcd().
930 * @param a first multivariate polynomial
931 * @param b second multivariate polynomial
932 * @param var iterator to first element of vector of sym_desc structs
933 * @return the GCD as a new expression
936 static ex sr_gcd(const ex &a, const ex &b, sym_desc_vec::const_iterator var)
942 // The first symbol is our main variable
943 const symbol &x = *(var->sym);
945 // Sort c and d so that c has higher degree
947 int adeg = a.degree(x), bdeg = b.degree(x);
961 // Remove content from c and d, to be attached to GCD later
962 ex cont_c = c.content(x);
963 ex cont_d = d.content(x);
964 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
967 c = c.primpart(x, cont_c);
968 d = d.primpart(x, cont_d);
970 // First element of subresultant sequence
971 ex r = _ex0, ri = _ex1, psi = _ex1;
972 int delta = cdeg - ddeg;
976 // Calculate polynomial pseudo-remainder
977 r = prem(c, d, x, false);
979 return gamma * d.primpart(x);
983 if (!divide_in_z(r, ri * pow(psi, delta), d, var))
984 throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
987 if (is_exactly_a<numeric>(r))
990 return gamma * r.primpart(x);
993 // Next element of subresultant sequence
994 ri = c.expand().lcoeff(x);
998 divide_in_z(pow(ri, delta), pow(psi, delta-1), psi, var+1);
1004 /** Return maximum (absolute value) coefficient of a polynomial.
1005 * This function is used internally by heur_gcd().
1007 * @param e expanded multivariate polynomial
1008 * @return maximum coefficient
1010 numeric ex::max_coefficient(void) const
1012 GINAC_ASSERT(bp!=0);
1013 return bp->max_coefficient();
1016 /** Implementation ex::max_coefficient().
1018 numeric basic::max_coefficient(void) const
1023 numeric numeric::max_coefficient(void) const
1028 numeric add::max_coefficient(void) const
1030 epvector::const_iterator it = seq.begin();
1031 epvector::const_iterator itend = seq.end();
1032 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1033 numeric cur_max = abs(ex_to<numeric>(overall_coeff));
1034 while (it != itend) {
1036 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
1037 a = abs(ex_to<numeric>(it->coeff));
1045 numeric mul::max_coefficient(void) const
1047 #ifdef DO_GINAC_ASSERT
1048 epvector::const_iterator it = seq.begin();
1049 epvector::const_iterator itend = seq.end();
1050 while (it != itend) {
1051 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
1054 #endif // def DO_GINAC_ASSERT
1055 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1056 return abs(ex_to<numeric>(overall_coeff));
1060 /** Apply symmetric modular homomorphism to an expanded multivariate
1061 * polynomial. This function is usually used internally by heur_gcd().
1064 * @return mapped polynomial
1066 ex basic::smod(const numeric &xi) const
1071 ex numeric::smod(const numeric &xi) const
1073 return GiNaC::smod(*this, xi);
1076 ex add::smod(const numeric &xi) const
1079 newseq.reserve(seq.size()+1);
1080 epvector::const_iterator it = seq.begin();
1081 epvector::const_iterator itend = seq.end();
1082 while (it != itend) {
1083 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
1084 numeric coeff = GiNaC::smod(ex_to<numeric>(it->coeff), xi);
1085 if (!coeff.is_zero())
1086 newseq.push_back(expair(it->rest, coeff));
1089 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1090 numeric coeff = GiNaC::smod(ex_to<numeric>(overall_coeff), xi);
1091 return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
1094 ex mul::smod(const numeric &xi) const
1096 #ifdef DO_GINAC_ASSERT
1097 epvector::const_iterator it = seq.begin();
1098 epvector::const_iterator itend = seq.end();
1099 while (it != itend) {
1100 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
1103 #endif // def DO_GINAC_ASSERT
1104 mul * mulcopyp = new mul(*this);
1105 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1106 mulcopyp->overall_coeff = GiNaC::smod(ex_to<numeric>(overall_coeff),xi);
1107 mulcopyp->clearflag(status_flags::evaluated);
1108 mulcopyp->clearflag(status_flags::hash_calculated);
1109 return mulcopyp->setflag(status_flags::dynallocated);
1113 /** xi-adic polynomial interpolation */
1114 static ex interpolate(const ex &gamma, const numeric &xi, const symbol &x, int degree_hint = 1)
1116 exvector g; g.reserve(degree_hint);
1118 numeric rxi = xi.inverse();
1119 for (int i=0; !e.is_zero(); i++) {
1121 g.push_back(gi * power(x, i));
1124 return (new add(g))->setflag(status_flags::dynallocated);
1127 /** Exception thrown by heur_gcd() to signal failure. */
1128 class gcdheu_failed {};
1130 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1131 * get_symbol_stats() must have been called previously with the input
1132 * polynomials and an iterator to the first element of the sym_desc vector
1133 * passed in. This function is used internally by gcd().
1135 * @param a first multivariate polynomial (expanded)
1136 * @param b second multivariate polynomial (expanded)
1137 * @param ca cofactor of polynomial a (returned), NULL to suppress
1138 * calculation of cofactor
1139 * @param cb cofactor of polynomial b (returned), NULL to suppress
1140 * calculation of cofactor
1141 * @param var iterator to first element of vector of sym_desc structs
1142 * @return the GCD as a new expression
1144 * @exception gcdheu_failed() */
1145 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
1151 // Algorithm only works for non-vanishing input polynomials
1152 if (a.is_zero() || b.is_zero())
1153 return (new fail())->setflag(status_flags::dynallocated);
1155 // GCD of two numeric values -> CLN
1156 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b)) {
1157 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1159 *ca = ex_to<numeric>(a) / g;
1161 *cb = ex_to<numeric>(b) / g;
1165 // The first symbol is our main variable
1166 const symbol &x = *(var->sym);
1168 // Remove integer content
1169 numeric gc = gcd(a.integer_content(), b.integer_content());
1170 numeric rgc = gc.inverse();
1173 int maxdeg = std::max(p.degree(x), q.degree(x));
1175 // Find evaluation point
1176 numeric mp = p.max_coefficient();
1177 numeric mq = q.max_coefficient();
1180 xi = mq * _num2 + _num2;
1182 xi = mp * _num2 + _num2;
1185 for (int t=0; t<6; t++) {
1186 if (xi.int_length() * maxdeg > 100000) {
1187 throw gcdheu_failed();
1190 // Apply evaluation homomorphism and calculate GCD
1192 ex gamma = heur_gcd(p.subs(x == xi), q.subs(x == xi), &cp, &cq, var+1).expand();
1193 if (!is_exactly_a<fail>(gamma)) {
1195 // Reconstruct polynomial from GCD of mapped polynomials
1196 ex g = interpolate(gamma, xi, x, maxdeg);
1198 // Remove integer content
1199 g /= g.integer_content();
1201 // If the calculated polynomial divides both p and q, this is the GCD
1203 if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1205 ex lc = g.lcoeff(x);
1206 if (is_exactly_a<numeric>(lc) && ex_to<numeric>(lc).is_negative())
1213 // Next evaluation point
1214 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1216 return (new fail())->setflag(status_flags::dynallocated);
1220 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1223 * @param a first multivariate polynomial
1224 * @param b second multivariate polynomial
1225 * @param check_args check whether a and b are polynomials with rational
1226 * coefficients (defaults to "true")
1227 * @return the GCD as a new expression */
1228 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1234 // GCD of numerics -> CLN
1235 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b)) {
1236 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1245 *ca = ex_to<numeric>(a) / g;
1247 *cb = ex_to<numeric>(b) / g;
1254 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))) {
1255 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1258 // Partially factored cases (to avoid expanding large expressions)
1259 if (is_exactly_a<mul>(a)) {
1260 if (is_exactly_a<mul>(b) && b.nops() > a.nops())
1263 size_t num = a.nops();
1264 exvector g; g.reserve(num);
1265 exvector acc_ca; acc_ca.reserve(num);
1267 for (size_t i=0; i<num; i++) {
1268 ex part_ca, part_cb;
1269 g.push_back(gcd(a.op(i), part_b, &part_ca, &part_cb, check_args));
1270 acc_ca.push_back(part_ca);
1274 *ca = (new mul(acc_ca))->setflag(status_flags::dynallocated);
1277 return (new mul(g))->setflag(status_flags::dynallocated);
1278 } else if (is_exactly_a<mul>(b)) {
1279 if (is_exactly_a<mul>(a) && a.nops() > b.nops())
1282 size_t num = b.nops();
1283 exvector g; g.reserve(num);
1284 exvector acc_cb; acc_cb.reserve(num);
1286 for (size_t i=0; i<num; i++) {
1287 ex part_ca, part_cb;
1288 g.push_back(gcd(part_a, b.op(i), &part_ca, &part_cb, check_args));
1289 acc_cb.push_back(part_cb);
1295 *cb = (new mul(acc_cb))->setflag(status_flags::dynallocated);
1296 return (new mul(g))->setflag(status_flags::dynallocated);
1300 // Input polynomials of the form poly^n are sometimes also trivial
1301 if (is_exactly_a<power>(a)) {
1303 if (is_exactly_a<power>(b)) {
1304 if (p.is_equal(b.op(0))) {
1305 // a = p^n, b = p^m, gcd = p^min(n, m)
1306 ex exp_a = a.op(1), exp_b = b.op(1);
1307 if (exp_a < exp_b) {
1311 *cb = power(p, exp_b - exp_a);
1312 return power(p, exp_a);
1315 *ca = power(p, exp_a - exp_b);
1318 return power(p, exp_b);
1322 if (p.is_equal(b)) {
1323 // a = p^n, b = p, gcd = p
1325 *ca = power(p, a.op(1) - 1);
1331 } else if (is_exactly_a<power>(b)) {
1333 if (p.is_equal(a)) {
1334 // a = p, b = p^n, gcd = p
1338 *cb = power(p, b.op(1) - 1);
1344 // Some trivial cases
1345 ex aex = a.expand(), bex = b.expand();
1346 if (aex.is_zero()) {
1353 if (bex.is_zero()) {
1360 if (aex.is_equal(_ex1) || bex.is_equal(_ex1)) {
1368 if (a.is_equal(b)) {
1377 // Gather symbol statistics
1378 sym_desc_vec sym_stats;
1379 get_symbol_stats(a, b, sym_stats);
1381 // The symbol with least degree is our main variable
1382 sym_desc_vec::const_iterator var = sym_stats.begin();
1383 const symbol &x = *(var->sym);
1385 // Cancel trivial common factor
1386 int ldeg_a = var->ldeg_a;
1387 int ldeg_b = var->ldeg_b;
1388 int min_ldeg = std::min(ldeg_a,ldeg_b);
1390 ex common = power(x, min_ldeg);
1391 return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1394 // Try to eliminate variables
1395 if (var->deg_a == 0) {
1396 ex c = bex.content(x);
1397 ex g = gcd(aex, c, ca, cb, false);
1399 *cb *= bex.unit(x) * bex.primpart(x, c);
1401 } else if (var->deg_b == 0) {
1402 ex c = aex.content(x);
1403 ex g = gcd(c, bex, ca, cb, false);
1405 *ca *= aex.unit(x) * aex.primpart(x, c);
1409 // Try heuristic algorithm first, fall back to PRS if that failed
1412 g = heur_gcd(aex, bex, ca, cb, var);
1413 } catch (gcdheu_failed) {
1416 if (is_exactly_a<fail>(g)) {
1420 g = sr_gcd(aex, bex, var);
1421 if (g.is_equal(_ex1)) {
1422 // Keep cofactors factored if possible
1429 divide(aex, g, *ca, false);
1431 divide(bex, g, *cb, false);
1434 if (g.is_equal(_ex1)) {
1435 // Keep cofactors factored if possible
1447 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1449 * @param a first multivariate polynomial
1450 * @param b second multivariate polynomial
1451 * @param check_args check whether a and b are polynomials with rational
1452 * coefficients (defaults to "true")
1453 * @return the LCM as a new expression */
1454 ex lcm(const ex &a, const ex &b, bool check_args)
1456 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b))
1457 return lcm(ex_to<numeric>(a), ex_to<numeric>(b));
1458 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
1459 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1462 ex g = gcd(a, b, &ca, &cb, false);
1468 * Square-free factorization
1471 /** Compute square-free factorization of multivariate polynomial a(x) using
1472 * YunĀ“s algorithm. Used internally by sqrfree().
1474 * @param a multivariate polynomial over Z[X], treated here as univariate
1476 * @param x variable to factor in
1477 * @return vector of factors sorted in ascending degree */
1478 static exvector sqrfree_yun(const ex &a, const symbol &x)
1484 if (g.is_equal(_ex1)) {
1495 } while (!z.is_zero());
1500 /** Compute a square-free factorization of a multivariate polynomial in Q[X].
1502 * @param a multivariate polynomial over Q[X]
1503 * @param x lst of variables to factor in, may be left empty for autodetection
1504 * @return a square-free factorization of \p a.
1507 * A polynomial \f$p(X) \in C[X]\f$ is said <EM>square-free</EM>
1508 * if, whenever any two polynomials \f$q(X)\f$ and \f$r(X)\f$
1511 * p(X) = q(X)^2 r(X),
1513 * we have \f$q(X) \in C\f$.
1514 * This means that \f$p(X)\f$ has no repeated factors, apart
1515 * eventually from constants.
1516 * Given a polynomial \f$p(X) \in C[X]\f$, we say that the
1519 * p(X) = b \cdot p_1(X)^{a_1} \cdot p_2(X)^{a_2} \cdots p_r(X)^{a_r}
1521 * is a <EM>square-free factorization</EM> of \f$p(X)\f$ if the
1522 * following conditions hold:
1523 * -# \f$b \in C\f$ and \f$b \neq 0\f$;
1524 * -# \f$a_i\f$ is a positive integer for \f$i = 1, \ldots, r\f$;
1525 * -# the degree of the polynomial \f$p_i\f$ is strictly positive
1526 * for \f$i = 1, \ldots, r\f$;
1527 * -# the polynomial \f$\Pi_{i=1}^r p_i(X)\f$ is square-free.
1529 * Square-free factorizations need not be unique. For example, if
1530 * \f$a_i\f$ is even, we could change the polynomial \f$p_i(X)\f$
1531 * into \f$-p_i(X)\f$.
1532 * Observe also that the factors \f$p_i(X)\f$ need not be irreducible
1535 ex sqrfree(const ex &a, const lst &l)
1537 if (is_exactly_a<numeric>(a) || // algorithm does not trap a==0
1538 is_a<symbol>(a)) // shortcut
1541 // If no lst of variables to factorize in was specified we have to
1542 // invent one now. Maybe one can optimize here by reversing the order
1543 // or so, I don't know.
1547 get_symbol_stats(a, _ex0, sdv);
1548 sym_desc_vec::const_iterator it = sdv.begin(), itend = sdv.end();
1549 while (it != itend) {
1550 args.append(*it->sym);
1557 // Find the symbol to factor in at this stage
1558 if (!is_a<symbol>(args.op(0)))
1559 throw (std::runtime_error("sqrfree(): invalid factorization variable"));
1560 const symbol &x = ex_to<symbol>(args.op(0));
1562 // convert the argument from something in Q[X] to something in Z[X]
1563 const numeric lcm = lcm_of_coefficients_denominators(a);
1564 const ex tmp = multiply_lcm(a,lcm);
1567 exvector factors = sqrfree_yun(tmp,x);
1569 // construct the next list of symbols with the first element popped
1571 newargs.remove_first();
1573 // recurse down the factors in remaining variables
1574 if (newargs.nops()>0) {
1575 exvector::iterator i = factors.begin();
1576 while (i != factors.end()) {
1577 *i = sqrfree(*i, newargs);
1582 // Done with recursion, now construct the final result
1584 exvector::const_iterator it = factors.begin(), itend = factors.end();
1585 for (int p = 1; it!=itend; ++it, ++p)
1586 result *= power(*it, p);
1588 // Yun's algorithm does not account for constant factors. (For univariate
1589 // polynomials it works only in the monic case.) We can correct this by
1590 // inserting what has been lost back into the result. For completeness
1591 // we'll also have to recurse down that factor in the remaining variables.
1592 if (newargs.nops()>0)
1593 result *= sqrfree(quo(tmp, result, x), newargs);
1595 result *= quo(tmp, result, x);
1597 // Put in the reational overall factor again and return
1598 return result * lcm.inverse();
1602 /** Compute square-free partial fraction decomposition of rational function
1605 * @param a rational function over Z[x], treated as univariate polynomial
1607 * @param x variable to factor in
1608 * @return decomposed rational function */
1609 ex sqrfree_parfrac(const ex & a, const symbol & x)
1611 // Find numerator and denominator
1612 ex nd = numer_denom(a);
1613 ex numer = nd.op(0), denom = nd.op(1);
1614 //clog << "numer = " << numer << ", denom = " << denom << endl;
1616 // Convert N(x)/D(x) -> Q(x) + R(x)/D(x), so degree(R) < degree(D)
1617 ex red_poly = quo(numer, denom, x), red_numer = rem(numer, denom, x).expand();
1618 //clog << "red_poly = " << red_poly << ", red_numer = " << red_numer << endl;
1620 // Factorize denominator and compute cofactors
1621 exvector yun = sqrfree_yun(denom, x);
1622 //clog << "yun factors: " << exprseq(yun) << endl;
1623 size_t num_yun = yun.size();
1624 exvector factor; factor.reserve(num_yun);
1625 exvector cofac; cofac.reserve(num_yun);
1626 for (size_t i=0; i<num_yun; i++) {
1627 if (!yun[i].is_equal(_ex1)) {
1628 for (size_t j=0; j<=i; j++) {
1629 factor.push_back(pow(yun[i], j+1));
1631 for (size_t k=0; k<num_yun; k++) {
1633 prod *= pow(yun[k], i-j);
1635 prod *= pow(yun[k], k+1);
1637 cofac.push_back(prod.expand());
1641 size_t num_factors = factor.size();
1642 //clog << "factors : " << exprseq(factor) << endl;
1643 //clog << "cofactors: " << exprseq(cofac) << endl;
1645 // Construct coefficient matrix for decomposition
1646 int max_denom_deg = denom.degree(x);
1647 matrix sys(max_denom_deg + 1, num_factors);
1648 matrix rhs(max_denom_deg + 1, 1);
1649 for (int i=0; i<=max_denom_deg; i++) {
1650 for (size_t j=0; j<num_factors; j++)
1651 sys(i, j) = cofac[j].coeff(x, i);
1652 rhs(i, 0) = red_numer.coeff(x, i);
1654 //clog << "coeffs: " << sys << endl;
1655 //clog << "rhs : " << rhs << endl;
1657 // Solve resulting linear system
1658 matrix vars(num_factors, 1);
1659 for (size_t i=0; i<num_factors; i++)
1660 vars(i, 0) = symbol();
1661 matrix sol = sys.solve(vars, rhs);
1663 // Sum up decomposed fractions
1665 for (size_t i=0; i<num_factors; i++)
1666 sum += sol(i, 0) / factor[i];
1668 return red_poly + sum;
1673 * Normal form of rational functions
1677 * Note: The internal normal() functions (= basic::normal() and overloaded
1678 * functions) all return lists of the form {numerator, denominator}. This
1679 * is to get around mul::eval()'s automatic expansion of numeric coefficients.
1680 * E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
1681 * the information that (a+b) is the numerator and 3 is the denominator.
1685 /** Create a symbol for replacing the expression "e" (or return a previously
1686 * assigned symbol). The symbol is appended to sym_lst and returned, the
1687 * expression is appended to repl_lst.
1688 * @see ex::normal */
1689 static ex replace_with_symbol(const ex &e, lst &sym_lst, lst &repl_lst)
1691 // Expression already in repl_lst? Then return the assigned symbol
1692 lst::const_iterator its, itr;
1693 for (its = sym_lst.begin(), itr = repl_lst.begin(); itr != repl_lst.end(); ++its, ++itr)
1694 if (itr->is_equal(e))
1697 // Otherwise create new symbol and add to list, taking care that the
1698 // replacement expression doesn't contain symbols from the sym_lst
1699 // because subs() is not recursive
1702 ex e_replaced = e.subs(sym_lst, repl_lst);
1704 repl_lst.append(e_replaced);
1708 /** Create a symbol for replacing the expression "e" (or return a previously
1709 * assigned symbol). An expression of the form "symbol == expression" is added
1710 * to repl_lst and the symbol is returned.
1711 * @see basic::to_rational
1712 * @see basic::to_polynomial */
1713 static ex replace_with_symbol(const ex &e, lst &repl_lst)
1715 // Expression already in repl_lst? Then return the assigned symbol
1716 for (lst::const_iterator it = repl_lst.begin(); it != repl_lst.end(); ++it)
1717 if (it->op(1).is_equal(e))
1720 // Otherwise create new symbol and add to list, taking care that the
1721 // replacement expression doesn't contain symbols from the sym_lst
1722 // because subs() is not recursive
1725 ex e_replaced = e.subs(repl_lst);
1726 repl_lst.append(es == e_replaced);
1731 /** Function object to be applied by basic::normal(). */
1732 struct normal_map_function : public map_function {
1734 normal_map_function(int l) : level(l) {}
1735 ex operator()(const ex & e) { return normal(e, level); }
1738 /** Default implementation of ex::normal(). It normalizes the children and
1739 * replaces the object with a temporary symbol.
1740 * @see ex::normal */
1741 ex basic::normal(lst &sym_lst, lst &repl_lst, int level) const
1744 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
1747 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
1748 else if (level == -max_recursion_level)
1749 throw(std::runtime_error("max recursion level reached"));
1751 normal_map_function map_normal(level - 1);
1752 return (new lst(replace_with_symbol(map(map_normal), sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
1758 /** Implementation of ex::normal() for symbols. This returns the unmodified symbol.
1759 * @see ex::normal */
1760 ex symbol::normal(lst &sym_lst, lst &repl_lst, int level) const
1762 return (new lst(*this, _ex1))->setflag(status_flags::dynallocated);
1766 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1767 * into re+I*im and replaces I and non-rational real numbers with a temporary
1769 * @see ex::normal */
1770 ex numeric::normal(lst &sym_lst, lst &repl_lst, int level) const
1772 numeric num = numer();
1775 if (num.is_real()) {
1776 if (!num.is_integer())
1777 numex = replace_with_symbol(numex, sym_lst, repl_lst);
1779 numeric re = num.real(), im = num.imag();
1780 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, sym_lst, repl_lst);
1781 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, sym_lst, repl_lst);
1782 numex = re_ex + im_ex * replace_with_symbol(I, sym_lst, repl_lst);
1785 // Denominator is always a real integer (see numeric::denom())
1786 return (new lst(numex, denom()))->setflag(status_flags::dynallocated);
1790 /** Fraction cancellation.
1791 * @param n numerator
1792 * @param d denominator
1793 * @return cancelled fraction {n, d} as a list */
1794 static ex frac_cancel(const ex &n, const ex &d)
1798 numeric pre_factor = _num1;
1800 //std::clog << "frac_cancel num = " << num << ", den = " << den << std::endl;
1802 // Handle trivial case where denominator is 1
1803 if (den.is_equal(_ex1))
1804 return (new lst(num, den))->setflag(status_flags::dynallocated);
1806 // Handle special cases where numerator or denominator is 0
1808 return (new lst(num, _ex1))->setflag(status_flags::dynallocated);
1809 if (den.expand().is_zero())
1810 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
1812 // Bring numerator and denominator to Z[X] by multiplying with
1813 // LCM of all coefficients' denominators
1814 numeric num_lcm = lcm_of_coefficients_denominators(num);
1815 numeric den_lcm = lcm_of_coefficients_denominators(den);
1816 num = multiply_lcm(num, num_lcm);
1817 den = multiply_lcm(den, den_lcm);
1818 pre_factor = den_lcm / num_lcm;
1820 // Cancel GCD from numerator and denominator
1822 if (gcd(num, den, &cnum, &cden, false) != _ex1) {
1827 // Make denominator unit normal (i.e. coefficient of first symbol
1828 // as defined by get_first_symbol() is made positive)
1830 if (get_first_symbol(den, x)) {
1831 GINAC_ASSERT(is_exactly_a<numeric>(den.unit(*x)));
1832 if (ex_to<numeric>(den.unit(*x)).is_negative()) {
1838 // Return result as list
1839 //std::clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << std::endl;
1840 return (new lst(num * pre_factor.numer(), den * pre_factor.denom()))->setflag(status_flags::dynallocated);
1844 /** Implementation of ex::normal() for a sum. It expands terms and performs
1845 * fractional addition.
1846 * @see ex::normal */
1847 ex add::normal(lst &sym_lst, lst &repl_lst, int level) const
1850 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
1851 else if (level == -max_recursion_level)
1852 throw(std::runtime_error("max recursion level reached"));
1854 // Normalize children and split each one into numerator and denominator
1855 exvector nums, dens;
1856 nums.reserve(seq.size()+1);
1857 dens.reserve(seq.size()+1);
1858 epvector::const_iterator it = seq.begin(), itend = seq.end();
1859 while (it != itend) {
1860 ex n = ex_to<basic>(recombine_pair_to_ex(*it)).normal(sym_lst, repl_lst, level-1);
1861 nums.push_back(n.op(0));
1862 dens.push_back(n.op(1));
1865 ex n = ex_to<numeric>(overall_coeff).normal(sym_lst, repl_lst, level-1);
1866 nums.push_back(n.op(0));
1867 dens.push_back(n.op(1));
1868 GINAC_ASSERT(nums.size() == dens.size());
1870 // Now, nums is a vector of all numerators and dens is a vector of
1872 //std::clog << "add::normal uses " << nums.size() << " summands:\n";
1874 // Add fractions sequentially
1875 exvector::const_iterator num_it = nums.begin(), num_itend = nums.end();
1876 exvector::const_iterator den_it = dens.begin(), den_itend = dens.end();
1877 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
1878 ex num = *num_it++, den = *den_it++;
1879 while (num_it != num_itend) {
1880 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
1881 ex next_num = *num_it++, next_den = *den_it++;
1883 // Trivially add sequences of fractions with identical denominators
1884 while ((den_it != den_itend) && next_den.is_equal(*den_it)) {
1885 next_num += *num_it;
1889 // Additiion of two fractions, taking advantage of the fact that
1890 // the heuristic GCD algorithm computes the cofactors at no extra cost
1891 ex co_den1, co_den2;
1892 ex g = gcd(den, next_den, &co_den1, &co_den2, false);
1893 num = ((num * co_den2) + (next_num * co_den1)).expand();
1894 den *= co_den2; // this is the lcm(den, next_den)
1896 //std::clog << " common denominator = " << den << std::endl;
1898 // Cancel common factors from num/den
1899 return frac_cancel(num, den);
1903 /** Implementation of ex::normal() for a product. It cancels common factors
1905 * @see ex::normal() */
1906 ex mul::normal(lst &sym_lst, lst &repl_lst, int level) const
1909 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
1910 else if (level == -max_recursion_level)
1911 throw(std::runtime_error("max recursion level reached"));
1913 // Normalize children, separate into numerator and denominator
1914 exvector num; num.reserve(seq.size());
1915 exvector den; den.reserve(seq.size());
1917 epvector::const_iterator it = seq.begin(), itend = seq.end();
1918 while (it != itend) {
1919 n = ex_to<basic>(recombine_pair_to_ex(*it)).normal(sym_lst, repl_lst, level-1);
1920 num.push_back(n.op(0));
1921 den.push_back(n.op(1));
1924 n = ex_to<numeric>(overall_coeff).normal(sym_lst, repl_lst, level-1);
1925 num.push_back(n.op(0));
1926 den.push_back(n.op(1));
1928 // Perform fraction cancellation
1929 return frac_cancel((new mul(num))->setflag(status_flags::dynallocated),
1930 (new mul(den))->setflag(status_flags::dynallocated));
1934 /** Implementation of ex::normal() for powers. It normalizes the basis,
1935 * distributes integer exponents to numerator and denominator, and replaces
1936 * non-integer powers by temporary symbols.
1937 * @see ex::normal */
1938 ex power::normal(lst &sym_lst, lst &repl_lst, int level) const
1941 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
1942 else if (level == -max_recursion_level)
1943 throw(std::runtime_error("max recursion level reached"));
1945 // Normalize basis and exponent (exponent gets reassembled)
1946 ex n_basis = ex_to<basic>(basis).normal(sym_lst, repl_lst, level-1);
1947 ex n_exponent = ex_to<basic>(exponent).normal(sym_lst, repl_lst, level-1);
1948 n_exponent = n_exponent.op(0) / n_exponent.op(1);
1950 if (n_exponent.info(info_flags::integer)) {
1952 if (n_exponent.info(info_flags::positive)) {
1954 // (a/b)^n -> {a^n, b^n}
1955 return (new lst(power(n_basis.op(0), n_exponent), power(n_basis.op(1), n_exponent)))->setflag(status_flags::dynallocated);
1957 } else if (n_exponent.info(info_flags::negative)) {
1959 // (a/b)^-n -> {b^n, a^n}
1960 return (new lst(power(n_basis.op(1), -n_exponent), power(n_basis.op(0), -n_exponent)))->setflag(status_flags::dynallocated);
1965 if (n_exponent.info(info_flags::positive)) {
1967 // (a/b)^x -> {sym((a/b)^x), 1}
1968 return (new lst(replace_with_symbol(power(n_basis.op(0) / n_basis.op(1), n_exponent), sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
1970 } else if (n_exponent.info(info_flags::negative)) {
1972 if (n_basis.op(1).is_equal(_ex1)) {
1974 // a^-x -> {1, sym(a^x)}
1975 return (new lst(_ex1, replace_with_symbol(power(n_basis.op(0), -n_exponent), sym_lst, repl_lst)))->setflag(status_flags::dynallocated);
1979 // (a/b)^-x -> {sym((b/a)^x), 1}
1980 return (new lst(replace_with_symbol(power(n_basis.op(1) / n_basis.op(0), -n_exponent), sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
1985 // (a/b)^x -> {sym((a/b)^x, 1}
1986 return (new lst(replace_with_symbol(power(n_basis.op(0) / n_basis.op(1), n_exponent), sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
1990 /** Implementation of ex::normal() for pseries. It normalizes each coefficient
1991 * and replaces the series by a temporary symbol.
1992 * @see ex::normal */
1993 ex pseries::normal(lst &sym_lst, lst &repl_lst, int level) const
1996 epvector::const_iterator i = seq.begin(), end = seq.end();
1998 ex restexp = i->rest.normal();
1999 if (!restexp.is_zero())
2000 newseq.push_back(expair(restexp, i->coeff));
2003 ex n = pseries(relational(var,point), newseq);
2004 return (new lst(replace_with_symbol(n, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
2008 /** Normalization of rational functions.
2009 * This function converts an expression to its normal form
2010 * "numerator/denominator", where numerator and denominator are (relatively
2011 * prime) polynomials. Any subexpressions which are not rational functions
2012 * (like non-rational numbers, non-integer powers or functions like sin(),
2013 * cos() etc.) are replaced by temporary symbols which are re-substituted by
2014 * the (normalized) subexpressions before normal() returns (this way, any
2015 * expression can be treated as a rational function). normal() is applied
2016 * recursively to arguments of functions etc.
2018 * @param level maximum depth of recursion
2019 * @return normalized expression */
2020 ex ex::normal(int level) const
2022 lst sym_lst, repl_lst;
2024 ex e = bp->normal(sym_lst, repl_lst, level);
2025 GINAC_ASSERT(is_a<lst>(e));
2027 // Re-insert replaced symbols
2028 if (sym_lst.nops() > 0)
2029 e = e.subs(sym_lst, repl_lst);
2031 // Convert {numerator, denominator} form back to fraction
2032 return e.op(0) / e.op(1);
2035 /** Get numerator of an expression. If the expression is not of the normal
2036 * form "numerator/denominator", it is first converted to this form and
2037 * then the numerator is returned.
2040 * @return numerator */
2041 ex ex::numer(void) const
2043 lst sym_lst, repl_lst;
2045 ex e = bp->normal(sym_lst, repl_lst, 0);
2046 GINAC_ASSERT(is_a<lst>(e));
2048 // Re-insert replaced symbols
2049 if (sym_lst.nops() > 0)
2050 return e.op(0).subs(sym_lst, repl_lst);
2055 /** Get denominator of an expression. If the expression is not of the normal
2056 * form "numerator/denominator", it is first converted to this form and
2057 * then the denominator is returned.
2060 * @return denominator */
2061 ex ex::denom(void) const
2063 lst sym_lst, repl_lst;
2065 ex e = bp->normal(sym_lst, repl_lst, 0);
2066 GINAC_ASSERT(is_a<lst>(e));
2068 // Re-insert replaced symbols
2069 if (sym_lst.nops() > 0)
2070 return e.op(1).subs(sym_lst, repl_lst);
2075 /** Get numerator and denominator of an expression. If the expresison is not
2076 * of the normal form "numerator/denominator", it is first converted to this
2077 * form and then a list [numerator, denominator] is returned.
2080 * @return a list [numerator, denominator] */
2081 ex ex::numer_denom(void) const
2083 lst sym_lst, repl_lst;
2085 ex e = bp->normal(sym_lst, repl_lst, 0);
2086 GINAC_ASSERT(is_a<lst>(e));
2088 // Re-insert replaced symbols
2089 if (sym_lst.nops() > 0)
2090 return e.subs(sym_lst, repl_lst);
2096 /** Rationalization of non-rational functions.
2097 * This function converts a general expression to a rational function
2098 * by replacing all non-rational subexpressions (like non-rational numbers,
2099 * non-integer powers or functions like sin(), cos() etc.) to temporary
2100 * symbols. This makes it possible to use functions like gcd() and divide()
2101 * on non-rational functions by applying to_rational() on the arguments,
2102 * calling the desired function and re-substituting the temporary symbols
2103 * in the result. To make the last step possible, all temporary symbols and
2104 * their associated expressions are collected in the list specified by the
2105 * repl_lst parameter in the form {symbol == expression}, ready to be passed
2106 * as an argument to ex::subs().
2108 * @param repl_lst collects a list of all temporary symbols and their replacements
2109 * @return rationalized expression */
2110 ex ex::to_rational(lst &repl_lst) const
2112 return bp->to_rational(repl_lst);
2115 ex ex::to_polynomial(lst &repl_lst) const
2117 return bp->to_polynomial(repl_lst);
2121 /** Default implementation of ex::to_rational(). This replaces the object with
2122 * a temporary symbol. */
2123 ex basic::to_rational(lst &repl_lst) const
2125 return replace_with_symbol(*this, repl_lst);
2128 ex basic::to_polynomial(lst &repl_lst) const
2130 return replace_with_symbol(*this, repl_lst);
2134 /** Implementation of ex::to_rational() for symbols. This returns the
2135 * unmodified symbol. */
2136 ex symbol::to_rational(lst &repl_lst) const
2141 /** Implementation of ex::to_polynomial() for symbols. This returns the
2142 * unmodified symbol. */
2143 ex symbol::to_polynomial(lst &repl_lst) const
2149 /** Implementation of ex::to_rational() for a numeric. It splits complex
2150 * numbers into re+I*im and replaces I and non-rational real numbers with a
2151 * temporary symbol. */
2152 ex numeric::to_rational(lst &repl_lst) const
2156 return replace_with_symbol(*this, repl_lst);
2158 numeric re = real();
2159 numeric im = imag();
2160 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl_lst);
2161 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl_lst);
2162 return re_ex + im_ex * replace_with_symbol(I, repl_lst);
2167 /** Implementation of ex::to_polynomial() for a numeric. It splits complex
2168 * numbers into re+I*im and replaces I and non-integer real numbers with a
2169 * temporary symbol. */
2170 ex numeric::to_polynomial(lst &repl_lst) const
2174 return replace_with_symbol(*this, repl_lst);
2176 numeric re = real();
2177 numeric im = imag();
2178 ex re_ex = re.is_integer() ? re : replace_with_symbol(re, repl_lst);
2179 ex im_ex = im.is_integer() ? im : replace_with_symbol(im, repl_lst);
2180 return re_ex + im_ex * replace_with_symbol(I, repl_lst);
2186 /** Implementation of ex::to_rational() for powers. It replaces non-integer
2187 * powers by temporary symbols. */
2188 ex power::to_rational(lst &repl_lst) const
2190 if (exponent.info(info_flags::integer))
2191 return power(basis.to_rational(repl_lst), exponent);
2193 return replace_with_symbol(*this, repl_lst);
2196 /** Implementation of ex::to_polynomial() for powers. It replaces non-posint
2197 * powers by temporary symbols. */
2198 ex power::to_polynomial(lst &repl_lst) const
2200 if (exponent.info(info_flags::posint))
2201 return power(basis.to_rational(repl_lst), exponent);
2203 return replace_with_symbol(*this, repl_lst);
2207 /** Implementation of ex::to_rational() for expairseqs. */
2208 ex expairseq::to_rational(lst &repl_lst) const
2211 s.reserve(seq.size());
2212 epvector::const_iterator i = seq.begin(), end = seq.end();
2214 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*i).to_rational(repl_lst)));
2217 ex oc = overall_coeff.to_rational(repl_lst);
2218 if (oc.info(info_flags::numeric))
2219 return thisexpairseq(s, overall_coeff);
2221 s.push_back(combine_ex_with_coeff_to_pair(oc, _ex1));
2222 return thisexpairseq(s, default_overall_coeff());
2225 /** Implementation of ex::to_polynomial() for expairseqs. */
2226 ex expairseq::to_polynomial(lst &repl_lst) const
2229 s.reserve(seq.size());
2230 epvector::const_iterator i = seq.begin(), end = seq.end();
2232 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*i).to_polynomial(repl_lst)));
2235 ex oc = overall_coeff.to_polynomial(repl_lst);
2236 if (oc.info(info_flags::numeric))
2237 return thisexpairseq(s, overall_coeff);
2239 s.push_back(combine_ex_with_coeff_to_pair(oc, _ex1));
2240 return thisexpairseq(s, default_overall_coeff());
2244 /** Remove the common factor in the terms of a sum 'e' by calculating the GCD,
2245 * and multiply it into the expression 'factor' (which needs to be initialized
2246 * to 1, unless you're accumulating factors). */
2247 static ex find_common_factor(const ex & e, ex & factor, lst & repl)
2249 if (is_exactly_a<add>(e)) {
2251 size_t num = e.nops();
2252 exvector terms; terms.reserve(num);
2255 // Find the common GCD
2256 for (size_t i=0; i<num; i++) {
2257 ex x = e.op(i).to_polynomial(repl);
2259 if (is_exactly_a<add>(x) || is_exactly_a<mul>(x)) {
2261 x = find_common_factor(x, f, repl);
2273 if (gc.is_equal(_ex1))
2276 // The GCD is the factor we pull out
2279 // Now divide all terms by the GCD
2280 for (size_t i=0; i<num; i++) {
2283 // Try to avoid divide() because it expands the polynomial
2285 if (is_exactly_a<mul>(t)) {
2286 for (size_t j=0; j<t.nops(); j++) {
2287 if (t.op(j).is_equal(gc)) {
2288 exvector v; v.reserve(t.nops());
2289 for (size_t k=0; k<t.nops(); k++) {
2293 v.push_back(t.op(k));
2295 t = (new mul(v))->setflag(status_flags::dynallocated);
2305 return (new add(terms))->setflag(status_flags::dynallocated);
2307 } else if (is_exactly_a<mul>(e)) {
2309 size_t num = e.nops();
2310 exvector v; v.reserve(num);
2312 for (size_t i=0; i<num; i++)
2313 v.push_back(find_common_factor(e.op(i), factor, repl));
2315 return (new mul(v))->setflag(status_flags::dynallocated);
2317 } else if (is_exactly_a<power>(e)) {
2319 return e.to_polynomial(repl);
2326 /** Collect common factors in sums. This converts expressions like
2327 * 'a*(b*x+b*y)' to 'a*b*(x+y)'. */
2328 ex collect_common_factors(const ex & e)
2330 if (is_exactly_a<add>(e) || is_exactly_a<mul>(e)) {
2334 ex r = find_common_factor(e, factor, repl);
2335 return factor.subs(repl) * r.subs(repl);
2342 } // namespace GiNaC