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-2001 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"
49 // If comparing expressions (ex::compare()) is fast, you can set this to 1.
50 // Some routines like quo(), rem() and gcd() will then return a quick answer
51 // when they are called with two identical arguments.
52 #define FAST_COMPARE 1
54 // Set this if you want divide_in_z() to use remembering
55 #define USE_REMEMBER 0
57 // Set this if you want divide_in_z() to use trial division followed by
58 // polynomial interpolation (always slower except for completely dense
60 #define USE_TRIAL_DIVISION 0
62 // Set this to enable some statistical output for the GCD routines
67 // Statistics variables
68 static int gcd_called = 0;
69 static int sr_gcd_called = 0;
70 static int heur_gcd_called = 0;
71 static int heur_gcd_failed = 0;
73 // Print statistics at end of program
74 static struct _stat_print {
77 cout << "gcd() called " << gcd_called << " times\n";
78 cout << "sr_gcd() called " << sr_gcd_called << " times\n";
79 cout << "heur_gcd() called " << heur_gcd_called << " times\n";
80 cout << "heur_gcd() failed " << heur_gcd_failed << " times\n";
86 /** Return pointer to first symbol found in expression. Due to GiNaCĀ“s
87 * internal ordering of terms, it may not be obvious which symbol this
88 * function returns for a given expression.
90 * @param e expression to search
91 * @param x pointer to first symbol found (returned)
92 * @return "false" if no symbol was found, "true" otherwise */
93 static bool get_first_symbol(const ex &e, const symbol *&x)
95 if (is_ex_exactly_of_type(e, symbol)) {
96 x = static_cast<symbol *>(e.bp);
98 } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
99 for (unsigned i=0; i<e.nops(); i++)
100 if (get_first_symbol(e.op(i), x))
102 } else if (is_ex_exactly_of_type(e, power)) {
103 if (get_first_symbol(e.op(0), x))
111 * Statistical information about symbols in polynomials
114 /** This structure holds information about the highest and lowest degrees
115 * in which a symbol appears in two multivariate polynomials "a" and "b".
116 * A vector of these structures with information about all symbols in
117 * two polynomials can be created with the function get_symbol_stats().
119 * @see get_symbol_stats */
121 /** Pointer to symbol */
124 /** Highest degree of symbol in polynomial "a" */
127 /** Highest degree of symbol in polynomial "b" */
130 /** Lowest degree of symbol in polynomial "a" */
133 /** Lowest degree of symbol in polynomial "b" */
136 /** Maximum of deg_a and deg_b (Used for sorting) */
139 /** Maximum number of terms of leading coefficient of symbol in both polynomials */
142 /** Commparison operator for sorting */
143 bool operator<(const sym_desc &x) const
145 if (max_deg == x.max_deg)
146 return max_lcnops < x.max_lcnops;
148 return max_deg < x.max_deg;
152 // Vector of sym_desc structures
153 typedef std::vector<sym_desc> sym_desc_vec;
155 // Add symbol the sym_desc_vec (used internally by get_symbol_stats())
156 static void add_symbol(const symbol *s, sym_desc_vec &v)
158 sym_desc_vec::const_iterator it = v.begin(), itend = v.end();
159 while (it != itend) {
160 if (it->sym->compare(*s) == 0) // If it's already in there, don't add it a second time
169 // Collect all symbols of an expression (used internally by get_symbol_stats())
170 static void collect_symbols(const ex &e, sym_desc_vec &v)
172 if (is_ex_exactly_of_type(e, symbol)) {
173 add_symbol(static_cast<symbol *>(e.bp), v);
174 } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
175 for (unsigned i=0; i<e.nops(); i++)
176 collect_symbols(e.op(i), v);
177 } else if (is_ex_exactly_of_type(e, power)) {
178 collect_symbols(e.op(0), v);
182 /** Collect statistical information about symbols in polynomials.
183 * This function fills in a vector of "sym_desc" structs which contain
184 * information about the highest and lowest degrees of all symbols that
185 * appear in two polynomials. The vector is then sorted by minimum
186 * degree (lowest to highest). The information gathered by this
187 * function is used by the GCD routines to identify trivial factors
188 * and to determine which variable to choose as the main variable
189 * for GCD computation.
191 * @param a first multivariate polynomial
192 * @param b second multivariate polynomial
193 * @param v vector of sym_desc structs (filled in) */
194 static void get_symbol_stats(const ex &a, const ex &b, sym_desc_vec &v)
196 collect_symbols(a.eval(), v); // eval() to expand assigned symbols
197 collect_symbols(b.eval(), v);
198 sym_desc_vec::iterator it = v.begin(), itend = v.end();
199 while (it != itend) {
200 int deg_a = a.degree(*(it->sym));
201 int deg_b = b.degree(*(it->sym));
204 it->max_deg = std::max(deg_a, deg_b);
205 it->max_lcnops = std::max(a.lcoeff(*(it->sym)).nops(), b.lcoeff(*(it->sym)).nops());
206 it->ldeg_a = a.ldegree(*(it->sym));
207 it->ldeg_b = b.ldegree(*(it->sym));
210 sort(v.begin(), v.end());
212 std::clog << "Symbols:\n";
213 it = v.begin(); itend = v.end();
214 while (it != itend) {
215 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;
216 std::clog << " lcoeff_a=" << a.lcoeff(*(it->sym)) << ", lcoeff_b=" << b.lcoeff(*(it->sym)) << endl;
224 * Computation of LCM of denominators of coefficients of a polynomial
227 // Compute LCM of denominators of coefficients by going through the
228 // expression recursively (used internally by lcm_of_coefficients_denominators())
229 static numeric lcmcoeff(const ex &e, const numeric &l)
231 if (e.info(info_flags::rational))
232 return lcm(ex_to<numeric>(e).denom(), l);
233 else if (is_ex_exactly_of_type(e, add)) {
235 for (unsigned i=0; i<e.nops(); i++)
236 c = lcmcoeff(e.op(i), c);
238 } else if (is_ex_exactly_of_type(e, mul)) {
240 for (unsigned i=0; i<e.nops(); i++)
241 c *= lcmcoeff(e.op(i), _num1());
243 } else if (is_ex_exactly_of_type(e, power)) {
244 if (is_ex_exactly_of_type(e.op(0), symbol))
247 return pow(lcmcoeff(e.op(0), l), ex_to<numeric>(e.op(1)));
252 /** Compute LCM of denominators of coefficients of a polynomial.
253 * Given a polynomial with rational coefficients, this function computes
254 * the LCM of the denominators of all coefficients. This can be used
255 * to bring a polynomial from Q[X] to Z[X].
257 * @param e multivariate polynomial (need not be expanded)
258 * @return LCM of denominators of coefficients */
259 static numeric lcm_of_coefficients_denominators(const ex &e)
261 return lcmcoeff(e, _num1());
264 /** Bring polynomial from Q[X] to Z[X] by multiplying in the previously
265 * determined LCM of the coefficient's denominators.
267 * @param e multivariate polynomial (need not be expanded)
268 * @param lcm LCM to multiply in */
269 static ex multiply_lcm(const ex &e, const numeric &lcm)
271 if (is_ex_exactly_of_type(e, mul)) {
272 unsigned num = e.nops();
273 exvector v; v.reserve(num + 1);
274 numeric lcm_accum = _num1();
275 for (unsigned i=0; i<e.nops(); i++) {
276 numeric op_lcm = lcmcoeff(e.op(i), _num1());
277 v.push_back(multiply_lcm(e.op(i), op_lcm));
280 v.push_back(lcm / lcm_accum);
281 return (new mul(v))->setflag(status_flags::dynallocated);
282 } else if (is_ex_exactly_of_type(e, add)) {
283 unsigned num = e.nops();
284 exvector v; v.reserve(num);
285 for (unsigned i=0; i<num; i++)
286 v.push_back(multiply_lcm(e.op(i), lcm));
287 return (new add(v))->setflag(status_flags::dynallocated);
288 } else if (is_ex_exactly_of_type(e, power)) {
289 if (is_ex_exactly_of_type(e.op(0), symbol))
292 return pow(multiply_lcm(e.op(0), lcm.power(ex_to<numeric>(e.op(1)).inverse())), e.op(1));
298 /** Compute the integer content (= GCD of all numeric coefficients) of an
299 * expanded polynomial.
301 * @param e expanded polynomial
302 * @return integer content */
303 numeric ex::integer_content(void) const
306 return bp->integer_content();
309 numeric basic::integer_content(void) const
314 numeric numeric::integer_content(void) const
319 numeric add::integer_content(void) const
321 epvector::const_iterator it = seq.begin();
322 epvector::const_iterator itend = seq.end();
324 while (it != itend) {
325 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
326 GINAC_ASSERT(is_ex_exactly_of_type(it->coeff,numeric));
327 c = gcd(ex_to<numeric>(it->coeff), c);
330 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
331 c = gcd(ex_to<numeric>(overall_coeff),c);
335 numeric mul::integer_content(void) const
337 #ifdef DO_GINAC_ASSERT
338 epvector::const_iterator it = seq.begin();
339 epvector::const_iterator itend = seq.end();
340 while (it != itend) {
341 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
344 #endif // def DO_GINAC_ASSERT
345 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
346 return abs(ex_to<numeric>(overall_coeff));
351 * Polynomial quotients and remainders
354 /** Quotient q(x) of polynomials a(x) and b(x) in Q[x].
355 * It satisfies a(x)=b(x)*q(x)+r(x).
357 * @param a first polynomial in x (dividend)
358 * @param b second polynomial in x (divisor)
359 * @param x a and b are polynomials in x
360 * @param check_args check whether a and b are polynomials with rational
361 * coefficients (defaults to "true")
362 * @return quotient of a and b in Q[x] */
363 ex quo(const ex &a, const ex &b, const symbol &x, bool check_args)
366 throw(std::overflow_error("quo: division by zero"));
367 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
373 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
374 throw(std::invalid_argument("quo: arguments must be polynomials over the rationals"));
376 // Polynomial long division
380 int bdeg = b.degree(x);
381 int rdeg = r.degree(x);
382 ex blcoeff = b.expand().coeff(x, bdeg);
383 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
384 exvector v; v.reserve(rdeg - bdeg + 1);
385 while (rdeg >= bdeg) {
386 ex term, rcoeff = r.coeff(x, rdeg);
387 if (blcoeff_is_numeric)
388 term = rcoeff / blcoeff;
390 if (!divide(rcoeff, blcoeff, term, false))
391 return (new fail())->setflag(status_flags::dynallocated);
393 term *= power(x, rdeg - bdeg);
395 r -= (term * b).expand();
400 return (new add(v))->setflag(status_flags::dynallocated);
404 /** Remainder r(x) of polynomials a(x) and b(x) in Q[x].
405 * It satisfies a(x)=b(x)*q(x)+r(x).
407 * @param a first polynomial in x (dividend)
408 * @param b second polynomial in x (divisor)
409 * @param x a and b are polynomials in x
410 * @param check_args check whether a and b are polynomials with rational
411 * coefficients (defaults to "true")
412 * @return remainder of a(x) and b(x) in Q[x] */
413 ex rem(const ex &a, const ex &b, const symbol &x, bool check_args)
416 throw(std::overflow_error("rem: division by zero"));
417 if (is_ex_exactly_of_type(a, numeric)) {
418 if (is_ex_exactly_of_type(b, numeric))
427 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
428 throw(std::invalid_argument("rem: arguments must be polynomials over the rationals"));
430 // Polynomial long division
434 int bdeg = b.degree(x);
435 int rdeg = r.degree(x);
436 ex blcoeff = b.expand().coeff(x, bdeg);
437 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
438 while (rdeg >= bdeg) {
439 ex term, rcoeff = r.coeff(x, rdeg);
440 if (blcoeff_is_numeric)
441 term = rcoeff / blcoeff;
443 if (!divide(rcoeff, blcoeff, term, false))
444 return (new fail())->setflag(status_flags::dynallocated);
446 term *= power(x, rdeg - bdeg);
447 r -= (term * b).expand();
456 /** Decompose rational function a(x)=N(x)/D(x) into P(x)+n(x)/D(x)
457 * with degree(n, x) < degree(D, x).
459 * @param a rational function in x
460 * @param x a is a function of x
461 * @return decomposed function. */
462 ex decomp_rational(const ex &a, const symbol &x)
464 ex nd = numer_denom(a);
465 ex numer = nd.op(0), denom = nd.op(1);
466 ex q = quo(numer, denom, x);
467 if (is_ex_exactly_of_type(q, fail))
470 return q + rem(numer, denom, x) / denom;
474 /** Pseudo-remainder of polynomials a(x) and b(x) in Z[x].
476 * @param a first polynomial in x (dividend)
477 * @param b second polynomial in x (divisor)
478 * @param x a and b are polynomials in x
479 * @param check_args check whether a and b are polynomials with rational
480 * coefficients (defaults to "true")
481 * @return pseudo-remainder of a(x) and b(x) in Z[x] */
482 ex prem(const ex &a, const ex &b, const symbol &x, bool check_args)
485 throw(std::overflow_error("prem: division by zero"));
486 if (is_ex_exactly_of_type(a, numeric)) {
487 if (is_ex_exactly_of_type(b, numeric))
492 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
493 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
495 // Polynomial long division
498 int rdeg = r.degree(x);
499 int bdeg = eb.degree(x);
502 blcoeff = eb.coeff(x, bdeg);
506 eb -= blcoeff * power(x, bdeg);
510 int delta = rdeg - bdeg + 1, i = 0;
511 while (rdeg >= bdeg && !r.is_zero()) {
512 ex rlcoeff = r.coeff(x, rdeg);
513 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
517 r -= rlcoeff * power(x, rdeg);
518 r = (blcoeff * r).expand() - term;
522 return power(blcoeff, delta - i) * r;
526 /** Sparse pseudo-remainder of polynomials a(x) and b(x) in Z[x].
528 * @param a first polynomial in x (dividend)
529 * @param b second polynomial in x (divisor)
530 * @param x a and b are polynomials in x
531 * @param check_args check whether a and b are polynomials with rational
532 * coefficients (defaults to "true")
533 * @return sparse pseudo-remainder of a(x) and b(x) in Z[x] */
534 ex sprem(const ex &a, const ex &b, const symbol &x, bool check_args)
537 throw(std::overflow_error("prem: division by zero"));
538 if (is_ex_exactly_of_type(a, numeric)) {
539 if (is_ex_exactly_of_type(b, numeric))
544 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
545 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
547 // Polynomial long division
550 int rdeg = r.degree(x);
551 int bdeg = eb.degree(x);
554 blcoeff = eb.coeff(x, bdeg);
558 eb -= blcoeff * power(x, bdeg);
562 while (rdeg >= bdeg && !r.is_zero()) {
563 ex rlcoeff = r.coeff(x, rdeg);
564 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
568 r -= rlcoeff * power(x, rdeg);
569 r = (blcoeff * r).expand() - term;
576 /** Exact polynomial division of a(X) by b(X) in Q[X].
578 * @param a first multivariate polynomial (dividend)
579 * @param b second multivariate polynomial (divisor)
580 * @param q quotient (returned)
581 * @param check_args check whether a and b are polynomials with rational
582 * coefficients (defaults to "true")
583 * @return "true" when exact division succeeds (quotient returned in q),
584 * "false" otherwise */
585 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
589 throw(std::overflow_error("divide: division by zero"));
592 if (is_ex_exactly_of_type(b, numeric)) {
595 } else if (is_ex_exactly_of_type(a, numeric))
603 if (check_args && (!a.info(info_flags::rational_polynomial) ||
604 !b.info(info_flags::rational_polynomial)))
605 throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
609 if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
610 throw(std::invalid_argument("invalid expression in divide()"));
612 // Polynomial long division (recursive)
616 int bdeg = b.degree(*x);
617 int rdeg = r.degree(*x);
618 ex blcoeff = b.expand().coeff(*x, bdeg);
619 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
620 exvector v; v.reserve(rdeg - bdeg + 1);
621 while (rdeg >= bdeg) {
622 ex term, rcoeff = r.coeff(*x, rdeg);
623 if (blcoeff_is_numeric)
624 term = rcoeff / blcoeff;
626 if (!divide(rcoeff, blcoeff, term, false))
628 term *= power(*x, rdeg - bdeg);
630 r -= (term * b).expand();
632 q = (new add(v))->setflag(status_flags::dynallocated);
646 typedef std::pair<ex, ex> ex2;
647 typedef std::pair<ex, bool> exbool;
650 bool operator() (const ex2 &p, const ex2 &q) const
652 int cmp = p.first.compare(q.first);
653 return ((cmp<0) || (!(cmp>0) && p.second.compare(q.second)<0));
657 typedef std::map<ex2, exbool, ex2_less> ex2_exbool_remember;
661 /** Exact polynomial division of a(X) by b(X) in Z[X].
662 * This functions works like divide() but the input and output polynomials are
663 * in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
664 * divide(), it doesnĀ“t check whether the input polynomials really are integer
665 * polynomials, so be careful of what you pass in. Also, you have to run
666 * get_symbol_stats() over the input polynomials before calling this function
667 * and pass an iterator to the first element of the sym_desc vector. This
668 * function is used internally by the heur_gcd().
670 * @param a first multivariate polynomial (dividend)
671 * @param b second multivariate polynomial (divisor)
672 * @param q quotient (returned)
673 * @param var iterator to first element of vector of sym_desc structs
674 * @return "true" when exact division succeeds (the quotient is returned in
675 * q), "false" otherwise.
676 * @see get_symbol_stats, heur_gcd */
677 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
681 throw(std::overflow_error("divide_in_z: division by zero"));
682 if (b.is_equal(_ex1())) {
686 if (is_ex_exactly_of_type(a, numeric)) {
687 if (is_ex_exactly_of_type(b, numeric)) {
689 return q.info(info_flags::integer);
702 static ex2_exbool_remember dr_remember;
703 ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
704 if (remembered != dr_remember.end()) {
705 q = remembered->second.first;
706 return remembered->second.second;
711 const symbol *x = var->sym;
714 int adeg = a.degree(*x), bdeg = b.degree(*x);
718 #if USE_TRIAL_DIVISION
720 // Trial division with polynomial interpolation
723 // Compute values at evaluation points 0..adeg
724 vector<numeric> alpha; alpha.reserve(adeg + 1);
725 exvector u; u.reserve(adeg + 1);
726 numeric point = _num0();
728 for (i=0; i<=adeg; i++) {
729 ex bs = b.subs(*x == point);
730 while (bs.is_zero()) {
732 bs = b.subs(*x == point);
734 if (!divide_in_z(a.subs(*x == point), bs, c, var+1))
736 alpha.push_back(point);
742 vector<numeric> rcp; rcp.reserve(adeg + 1);
743 rcp.push_back(_num0());
744 for (k=1; k<=adeg; k++) {
745 numeric product = alpha[k] - alpha[0];
747 product *= alpha[k] - alpha[i];
748 rcp.push_back(product.inverse());
751 // Compute Newton coefficients
752 exvector v; v.reserve(adeg + 1);
754 for (k=1; k<=adeg; k++) {
756 for (i=k-2; i>=0; i--)
757 temp = temp * (alpha[k] - alpha[i]) + v[i];
758 v.push_back((u[k] - temp) * rcp[k]);
761 // Convert from Newton form to standard form
763 for (k=adeg-1; k>=0; k--)
764 c = c * (*x - alpha[k]) + v[k];
766 if (c.degree(*x) == (adeg - bdeg)) {
774 // Polynomial long division (recursive)
780 ex blcoeff = eb.coeff(*x, bdeg);
781 exvector v; v.reserve(rdeg - bdeg + 1);
782 while (rdeg >= bdeg) {
783 ex term, rcoeff = r.coeff(*x, rdeg);
784 if (!divide_in_z(rcoeff, blcoeff, term, var+1))
786 term = (term * power(*x, rdeg - bdeg)).expand();
788 r -= (term * eb).expand();
790 q = (new add(v))->setflag(status_flags::dynallocated);
792 dr_remember[ex2(a, b)] = exbool(q, true);
799 dr_remember[ex2(a, b)] = exbool(q, false);
808 * Separation of unit part, content part and primitive part of polynomials
811 /** Compute unit part (= sign of leading coefficient) of a multivariate
812 * polynomial in Z[x]. The product of unit part, content part, and primitive
813 * part is the polynomial itself.
815 * @param x variable in which to compute the unit part
817 * @see ex::content, ex::primpart */
818 ex ex::unit(const symbol &x) const
820 ex c = expand().lcoeff(x);
821 if (is_ex_exactly_of_type(c, numeric))
822 return c < _ex0() ? _ex_1() : _ex1();
825 if (get_first_symbol(c, y))
828 throw(std::invalid_argument("invalid expression in unit()"));
833 /** Compute content part (= unit normal GCD of all coefficients) of a
834 * multivariate polynomial in Z[x]. The product of unit part, content part,
835 * and primitive part is the polynomial itself.
837 * @param x variable in which to compute the content part
838 * @return content part
839 * @see ex::unit, ex::primpart */
840 ex ex::content(const symbol &x) const
844 if (is_ex_exactly_of_type(*this, numeric))
845 return info(info_flags::negative) ? -*this : *this;
850 // First, try the integer content
851 ex c = e.integer_content();
853 ex lcoeff = r.lcoeff(x);
854 if (lcoeff.info(info_flags::integer))
857 // GCD of all coefficients
858 int deg = e.degree(x);
859 int ldeg = e.ldegree(x);
861 return e.lcoeff(x) / e.unit(x);
863 for (int i=ldeg; i<=deg; i++)
864 c = gcd(e.coeff(x, i), c, NULL, NULL, false);
869 /** Compute primitive part of a multivariate polynomial in Z[x].
870 * The product of unit part, content part, and primitive part is the
873 * @param x variable in which to compute the primitive part
874 * @return primitive part
875 * @see ex::unit, ex::content */
876 ex ex::primpart(const symbol &x) const
880 if (is_ex_exactly_of_type(*this, numeric))
887 if (is_ex_exactly_of_type(c, numeric))
888 return *this / (c * u);
890 return quo(*this, c * u, x, false);
894 /** Compute primitive part of a multivariate polynomial in Z[x] when the
895 * content part is already known. This function is faster in computing the
896 * primitive part than the previous function.
898 * @param x variable in which to compute the primitive part
899 * @param c previously computed content part
900 * @return primitive part */
901 ex ex::primpart(const symbol &x, const ex &c) const
907 if (is_ex_exactly_of_type(*this, numeric))
911 if (is_ex_exactly_of_type(c, numeric))
912 return *this / (c * u);
914 return quo(*this, c * u, x, false);
919 * GCD of multivariate polynomials
922 /** Compute GCD of polynomials in Q[X] using the Euclidean algorithm (not
923 * really suited for multivariate GCDs). This function is only provided for
926 * @param a first multivariate polynomial
927 * @param b second multivariate polynomial
928 * @param x pointer to symbol (main variable) in which to compute the GCD in
929 * @return the GCD as a new expression
932 static ex eu_gcd(const ex &a, const ex &b, const symbol *x)
934 //std::clog << "eu_gcd(" << a << "," << b << ")\n";
936 // Sort c and d so that c has higher degree
938 int adeg = a.degree(*x), bdeg = b.degree(*x);
948 c = c / c.lcoeff(*x);
949 d = d / d.lcoeff(*x);
951 // Euclidean algorithm
954 //std::clog << " d = " << d << endl;
955 r = rem(c, d, *x, false);
957 return d / d.lcoeff(*x);
964 /** Compute GCD of multivariate polynomials using the Euclidean PRS algorithm
965 * with pseudo-remainders ("World's Worst GCD Algorithm", staying in Z[X]).
966 * This function is only provided for testing purposes.
968 * @param a first multivariate polynomial
969 * @param b second multivariate polynomial
970 * @param x pointer to symbol (main variable) in which to compute the GCD in
971 * @return the GCD as a new expression
974 static ex euprem_gcd(const ex &a, const ex &b, const symbol *x)
976 //std::clog << "euprem_gcd(" << a << "," << b << ")\n";
978 // Sort c and d so that c has higher degree
980 int adeg = a.degree(*x), bdeg = b.degree(*x);
989 // Calculate GCD of contents
990 ex gamma = gcd(c.content(*x), d.content(*x), NULL, NULL, false);
992 // Euclidean algorithm with pseudo-remainders
995 //std::clog << " d = " << d << endl;
996 r = prem(c, d, *x, false);
998 return d.primpart(*x) * gamma;
1005 /** Compute GCD of multivariate polynomials using the primitive Euclidean
1006 * PRS algorithm (complete content removal at each step). This function is
1007 * only provided for testing purposes.
1009 * @param a first multivariate polynomial
1010 * @param b second multivariate polynomial
1011 * @param x pointer to symbol (main variable) in which to compute the GCD in
1012 * @return the GCD as a new expression
1015 static ex peu_gcd(const ex &a, const ex &b, const symbol *x)
1017 //std::clog << "peu_gcd(" << a << "," << b << ")\n";
1019 // Sort c and d so that c has higher degree
1021 int adeg = a.degree(*x), bdeg = b.degree(*x);
1033 // Remove content from c and d, to be attached to GCD later
1034 ex cont_c = c.content(*x);
1035 ex cont_d = d.content(*x);
1036 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1039 c = c.primpart(*x, cont_c);
1040 d = d.primpart(*x, cont_d);
1042 // Euclidean algorithm with content removal
1045 //std::clog << " d = " << d << endl;
1046 r = prem(c, d, *x, false);
1055 /** Compute GCD of multivariate polynomials using the reduced PRS algorithm.
1056 * This function is only provided for testing purposes.
1058 * @param a first multivariate polynomial
1059 * @param b second multivariate polynomial
1060 * @param x pointer to symbol (main variable) in which to compute the GCD in
1061 * @return the GCD as a new expression
1064 static ex red_gcd(const ex &a, const ex &b, const symbol *x)
1066 //std::clog << "red_gcd(" << a << "," << b << ")\n";
1068 // Sort c and d so that c has higher degree
1070 int adeg = a.degree(*x), bdeg = b.degree(*x);
1084 // Remove content from c and d, to be attached to GCD later
1085 ex cont_c = c.content(*x);
1086 ex cont_d = d.content(*x);
1087 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1090 c = c.primpart(*x, cont_c);
1091 d = d.primpart(*x, cont_d);
1093 // First element of divisor sequence
1095 int delta = cdeg - ddeg;
1098 // Calculate polynomial pseudo-remainder
1099 //std::clog << " d = " << d << endl;
1100 r = prem(c, d, *x, false);
1102 return gamma * d.primpart(*x);
1106 if (!divide(r, pow(ri, delta), d, false))
1107 throw(std::runtime_error("invalid expression in red_gcd(), division failed"));
1108 ddeg = d.degree(*x);
1110 if (is_ex_exactly_of_type(r, numeric))
1113 return gamma * r.primpart(*x);
1116 ri = c.expand().lcoeff(*x);
1117 delta = cdeg - ddeg;
1122 /** Compute GCD of multivariate polynomials using the subresultant PRS
1123 * algorithm. This function is used internally by gcd().
1125 * @param a first multivariate polynomial
1126 * @param b second multivariate polynomial
1127 * @param var iterator to first element of vector of sym_desc structs
1128 * @return the GCD as a new expression
1131 static ex sr_gcd(const ex &a, const ex &b, sym_desc_vec::const_iterator var)
1133 //std::clog << "sr_gcd(" << a << "," << b << ")\n";
1138 // The first symbol is our main variable
1139 const symbol &x = *(var->sym);
1141 // Sort c and d so that c has higher degree
1143 int adeg = a.degree(x), bdeg = b.degree(x);
1157 // Remove content from c and d, to be attached to GCD later
1158 ex cont_c = c.content(x);
1159 ex cont_d = d.content(x);
1160 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1163 c = c.primpart(x, cont_c);
1164 d = d.primpart(x, cont_d);
1165 //std::clog << " content " << gamma << " removed, continuing with sr_gcd(" << c << "," << d << ")\n";
1167 // First element of subresultant sequence
1168 ex r = _ex0(), ri = _ex1(), psi = _ex1();
1169 int delta = cdeg - ddeg;
1172 // Calculate polynomial pseudo-remainder
1173 //std::clog << " start of loop, psi = " << psi << ", calculating pseudo-remainder...\n";
1174 //std::clog << " d = " << d << endl;
1175 r = prem(c, d, x, false);
1177 return gamma * d.primpart(x);
1180 //std::clog << " dividing...\n";
1181 if (!divide_in_z(r, ri * pow(psi, delta), d, var))
1182 throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
1185 if (is_ex_exactly_of_type(r, numeric))
1188 return gamma * r.primpart(x);
1191 // Next element of subresultant sequence
1192 //std::clog << " calculating next subresultant...\n";
1193 ri = c.expand().lcoeff(x);
1197 divide_in_z(pow(ri, delta), pow(psi, delta-1), psi, var+1);
1198 delta = cdeg - ddeg;
1203 /** Return maximum (absolute value) coefficient of a polynomial.
1204 * This function is used internally by heur_gcd().
1206 * @param e expanded multivariate polynomial
1207 * @return maximum coefficient
1209 numeric ex::max_coefficient(void) const
1211 GINAC_ASSERT(bp!=0);
1212 return bp->max_coefficient();
1215 /** Implementation ex::max_coefficient().
1217 numeric basic::max_coefficient(void) const
1222 numeric numeric::max_coefficient(void) const
1227 numeric add::max_coefficient(void) const
1229 epvector::const_iterator it = seq.begin();
1230 epvector::const_iterator itend = seq.end();
1231 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1232 numeric cur_max = abs(ex_to<numeric>(overall_coeff));
1233 while (it != itend) {
1235 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
1236 a = abs(ex_to<numeric>(it->coeff));
1244 numeric mul::max_coefficient(void) const
1246 #ifdef DO_GINAC_ASSERT
1247 epvector::const_iterator it = seq.begin();
1248 epvector::const_iterator itend = seq.end();
1249 while (it != itend) {
1250 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
1253 #endif // def DO_GINAC_ASSERT
1254 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1255 return abs(ex_to<numeric>(overall_coeff));
1259 /** Apply symmetric modular homomorphism to a multivariate polynomial.
1260 * This function is used internally by heur_gcd().
1262 * @param e expanded multivariate polynomial
1264 * @return mapped polynomial
1266 ex ex::smod(const numeric &xi) const
1268 GINAC_ASSERT(bp!=0);
1269 return bp->smod(xi);
1272 ex basic::smod(const numeric &xi) const
1277 ex numeric::smod(const numeric &xi) const
1279 return GiNaC::smod(*this, xi);
1282 ex add::smod(const numeric &xi) const
1285 newseq.reserve(seq.size()+1);
1286 epvector::const_iterator it = seq.begin();
1287 epvector::const_iterator itend = seq.end();
1288 while (it != itend) {
1289 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
1290 numeric coeff = GiNaC::smod(ex_to<numeric>(it->coeff), xi);
1291 if (!coeff.is_zero())
1292 newseq.push_back(expair(it->rest, coeff));
1295 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1296 numeric coeff = GiNaC::smod(ex_to<numeric>(overall_coeff), xi);
1297 return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
1300 ex mul::smod(const numeric &xi) const
1302 #ifdef DO_GINAC_ASSERT
1303 epvector::const_iterator it = seq.begin();
1304 epvector::const_iterator itend = seq.end();
1305 while (it != itend) {
1306 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
1309 #endif // def DO_GINAC_ASSERT
1310 mul * mulcopyp = new mul(*this);
1311 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1312 mulcopyp->overall_coeff = GiNaC::smod(ex_to<numeric>(overall_coeff),xi);
1313 mulcopyp->clearflag(status_flags::evaluated);
1314 mulcopyp->clearflag(status_flags::hash_calculated);
1315 return mulcopyp->setflag(status_flags::dynallocated);
1319 /** xi-adic polynomial interpolation */
1320 static ex interpolate(const ex &gamma, const numeric &xi, const symbol &x, int degree_hint = 1)
1322 exvector g; g.reserve(degree_hint);
1324 numeric rxi = xi.inverse();
1325 for (int i=0; !e.is_zero(); i++) {
1327 g.push_back(gi * power(x, i));
1330 return (new add(g))->setflag(status_flags::dynallocated);
1333 /** Exception thrown by heur_gcd() to signal failure. */
1334 class gcdheu_failed {};
1336 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1337 * get_symbol_stats() must have been called previously with the input
1338 * polynomials and an iterator to the first element of the sym_desc vector
1339 * passed in. This function is used internally by gcd().
1341 * @param a first multivariate polynomial (expanded)
1342 * @param b second multivariate polynomial (expanded)
1343 * @param ca cofactor of polynomial a (returned), NULL to suppress
1344 * calculation of cofactor
1345 * @param cb cofactor of polynomial b (returned), NULL to suppress
1346 * calculation of cofactor
1347 * @param var iterator to first element of vector of sym_desc structs
1348 * @return the GCD as a new expression
1350 * @exception gcdheu_failed() */
1351 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
1353 //std::clog << "heur_gcd(" << a << "," << b << ")\n";
1358 // Algorithm only works for non-vanishing input polynomials
1359 if (a.is_zero() || b.is_zero())
1360 return (new fail())->setflag(status_flags::dynallocated);
1362 // GCD of two numeric values -> CLN
1363 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1364 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1366 *ca = ex_to<numeric>(a) / g;
1368 *cb = ex_to<numeric>(b) / g;
1372 // The first symbol is our main variable
1373 const symbol &x = *(var->sym);
1375 // Remove integer content
1376 numeric gc = gcd(a.integer_content(), b.integer_content());
1377 numeric rgc = gc.inverse();
1380 int maxdeg = std::max(p.degree(x), q.degree(x));
1382 // Find evaluation point
1383 numeric mp = p.max_coefficient();
1384 numeric mq = q.max_coefficient();
1387 xi = mq * _num2() + _num2();
1389 xi = mp * _num2() + _num2();
1392 for (int t=0; t<6; t++) {
1393 if (xi.int_length() * maxdeg > 100000) {
1394 //std::clog << "giving up heur_gcd, xi.int_length = " << xi.int_length() << ", maxdeg = " << maxdeg << std::endl;
1395 throw gcdheu_failed();
1398 // Apply evaluation homomorphism and calculate GCD
1400 ex gamma = heur_gcd(p.subs(x == xi), q.subs(x == xi), &cp, &cq, var+1).expand();
1401 if (!is_ex_exactly_of_type(gamma, fail)) {
1403 // Reconstruct polynomial from GCD of mapped polynomials
1404 ex g = interpolate(gamma, xi, x, maxdeg);
1406 // Remove integer content
1407 g /= g.integer_content();
1409 // If the calculated polynomial divides both p and q, this is the GCD
1411 if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1413 ex lc = g.lcoeff(x);
1414 if (is_ex_exactly_of_type(lc, numeric) && ex_to<numeric>(lc).is_negative())
1420 cp = interpolate(cp, xi, x);
1421 if (divide_in_z(cp, p, g, var)) {
1422 if (divide_in_z(g, q, cb ? *cb : dummy, var)) {
1426 ex lc = g.lcoeff(x);
1427 if (is_ex_exactly_of_type(lc, numeric) && ex_to<numeric>(lc).is_negative())
1433 cq = interpolate(cq, xi, x);
1434 if (divide_in_z(cq, q, g, var)) {
1435 if (divide_in_z(g, p, ca ? *ca : dummy, var)) {
1439 ex lc = g.lcoeff(x);
1440 if (is_ex_exactly_of_type(lc, numeric) && ex_to<numeric>(lc).is_negative())
1449 // Next evaluation point
1450 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1452 return (new fail())->setflag(status_flags::dynallocated);
1456 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1459 * @param a first multivariate polynomial
1460 * @param b second multivariate polynomial
1461 * @param check_args check whether a and b are polynomials with rational
1462 * coefficients (defaults to "true")
1463 * @return the GCD as a new expression */
1464 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1466 //std::clog << "gcd(" << a << "," << b << ")\n";
1471 // GCD of numerics -> CLN
1472 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1473 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1482 *ca = ex_to<numeric>(a) / g;
1484 *cb = ex_to<numeric>(b) / g;
1491 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))) {
1492 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1495 // Partially factored cases (to avoid expanding large expressions)
1496 if (is_ex_exactly_of_type(a, mul)) {
1497 if (is_ex_exactly_of_type(b, mul) && b.nops() > a.nops())
1500 unsigned num = a.nops();
1501 exvector g; g.reserve(num);
1502 exvector acc_ca; acc_ca.reserve(num);
1504 for (unsigned i=0; i<num; i++) {
1505 ex part_ca, part_cb;
1506 g.push_back(gcd(a.op(i), part_b, &part_ca, &part_cb, check_args));
1507 acc_ca.push_back(part_ca);
1511 *ca = (new mul(acc_ca))->setflag(status_flags::dynallocated);
1514 return (new mul(g))->setflag(status_flags::dynallocated);
1515 } else if (is_ex_exactly_of_type(b, mul)) {
1516 if (is_ex_exactly_of_type(a, mul) && a.nops() > b.nops())
1519 unsigned num = b.nops();
1520 exvector g; g.reserve(num);
1521 exvector acc_cb; acc_cb.reserve(num);
1523 for (unsigned i=0; i<num; i++) {
1524 ex part_ca, part_cb;
1525 g.push_back(gcd(part_a, b.op(i), &part_ca, &part_cb, check_args));
1526 acc_cb.push_back(part_cb);
1532 *cb = (new mul(acc_cb))->setflag(status_flags::dynallocated);
1533 return (new mul(g))->setflag(status_flags::dynallocated);
1537 // Input polynomials of the form poly^n are sometimes also trivial
1538 if (is_ex_exactly_of_type(a, power)) {
1540 if (is_ex_exactly_of_type(b, power)) {
1541 if (p.is_equal(b.op(0))) {
1542 // a = p^n, b = p^m, gcd = p^min(n, m)
1543 ex exp_a = a.op(1), exp_b = b.op(1);
1544 if (exp_a < exp_b) {
1548 *cb = power(p, exp_b - exp_a);
1549 return power(p, exp_a);
1552 *ca = power(p, exp_a - exp_b);
1555 return power(p, exp_b);
1559 if (p.is_equal(b)) {
1560 // a = p^n, b = p, gcd = p
1562 *ca = power(p, a.op(1) - 1);
1568 } else if (is_ex_exactly_of_type(b, power)) {
1570 if (p.is_equal(a)) {
1571 // a = p, b = p^n, gcd = p
1575 *cb = power(p, b.op(1) - 1);
1581 // Some trivial cases
1582 ex aex = a.expand(), bex = b.expand();
1583 if (aex.is_zero()) {
1590 if (bex.is_zero()) {
1597 if (aex.is_equal(_ex1()) || bex.is_equal(_ex1())) {
1605 if (a.is_equal(b)) {
1614 // Gather symbol statistics
1615 sym_desc_vec sym_stats;
1616 get_symbol_stats(a, b, sym_stats);
1618 // The symbol with least degree is our main variable
1619 sym_desc_vec::const_iterator var = sym_stats.begin();
1620 const symbol &x = *(var->sym);
1622 // Cancel trivial common factor
1623 int ldeg_a = var->ldeg_a;
1624 int ldeg_b = var->ldeg_b;
1625 int min_ldeg = std::min(ldeg_a,ldeg_b);
1627 ex common = power(x, min_ldeg);
1628 //std::clog << "trivial common factor " << common << std::endl;
1629 return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1632 // Try to eliminate variables
1633 if (var->deg_a == 0) {
1634 //std::clog << "eliminating variable " << x << " from b" << std::endl;
1635 ex c = bex.content(x);
1636 ex g = gcd(aex, c, ca, cb, false);
1638 *cb *= bex.unit(x) * bex.primpart(x, c);
1640 } else if (var->deg_b == 0) {
1641 //std::clog << "eliminating variable " << x << " from a" << std::endl;
1642 ex c = aex.content(x);
1643 ex g = gcd(c, bex, ca, cb, false);
1645 *ca *= aex.unit(x) * aex.primpart(x, c);
1651 // Try heuristic algorithm first, fall back to PRS if that failed
1653 g = heur_gcd(aex, bex, ca, cb, var);
1654 } catch (gcdheu_failed) {
1657 if (is_ex_exactly_of_type(g, fail)) {
1658 //std::clog << "heuristics failed" << std::endl;
1663 // g = heur_gcd(aex, bex, ca, cb, var);
1664 // g = eu_gcd(aex, bex, &x);
1665 // g = euprem_gcd(aex, bex, &x);
1666 // g = peu_gcd(aex, bex, &x);
1667 // g = red_gcd(aex, bex, &x);
1668 g = sr_gcd(aex, bex, var);
1669 if (g.is_equal(_ex1())) {
1670 // Keep cofactors factored if possible
1677 divide(aex, g, *ca, false);
1679 divide(bex, g, *cb, false);
1683 if (g.is_equal(_ex1())) {
1684 // Keep cofactors factored if possible
1696 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1698 * @param a first multivariate polynomial
1699 * @param b second multivariate polynomial
1700 * @param check_args check whether a and b are polynomials with rational
1701 * coefficients (defaults to "true")
1702 * @return the LCM as a new expression */
1703 ex lcm(const ex &a, const ex &b, bool check_args)
1705 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
1706 return lcm(ex_to<numeric>(a), ex_to<numeric>(b));
1707 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
1708 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1711 ex g = gcd(a, b, &ca, &cb, false);
1717 * Square-free factorization
1720 /** Compute square-free factorization of multivariate polynomial a(x) using
1721 * YunĀ“s algorithm. Used internally by sqrfree().
1723 * @param a multivariate polynomial over Z[X], treated here as univariate
1725 * @param x variable to factor in
1726 * @return vector of factors sorted in ascending degree */
1727 static exvector sqrfree_yun(const ex &a, const symbol &x)
1733 if (g.is_equal(_ex1())) {
1744 } while (!z.is_zero());
1748 /** Compute square-free factorization of multivariate polynomial in Q[X].
1750 * @param a multivariate polynomial over Q[X]
1751 * @param x lst of variables to factor in, may be left empty for autodetection
1752 * @return polynomail a in square-free factored form. */
1753 ex sqrfree(const ex &a, const lst &l)
1755 if (is_ex_of_type(a,numeric) || // algorithm does not trap a==0
1756 is_ex_of_type(a,symbol)) // shortcut
1759 // If no lst of variables to factorize in was specified we have to
1760 // invent one now. Maybe one can optimize here by reversing the order
1761 // or so, I don't know.
1765 get_symbol_stats(a, _ex0(), sdv);
1766 sym_desc_vec::const_iterator it = sdv.begin(), itend = sdv.end();
1767 while (it != itend) {
1768 args.append(*it->sym);
1775 // Find the symbol to factor in at this stage
1776 if (!is_ex_of_type(args.op(0), symbol))
1777 throw (std::runtime_error("sqrfree(): invalid factorization variable"));
1778 const symbol x = ex_to<symbol>(args.op(0));
1780 // convert the argument from something in Q[X] to something in Z[X]
1781 numeric lcm = lcm_of_coefficients_denominators(a);
1782 ex tmp = multiply_lcm(a,lcm);
1785 exvector factors = sqrfree_yun(tmp,x);
1787 // construct the next list of symbols with the first element popped
1789 newargs.remove_first();
1791 // recurse down the factors in remaining vars
1792 if (newargs.nops()>0) {
1793 exvector::iterator i = factors.begin(), end = factors.end();
1795 *i = sqrfree(*i, newargs);
1800 // Done with recursion, now construct the final result
1802 exvector::const_iterator it = factors.begin(), itend = factors.end();
1803 for (int p = 1; it!=itend; ++it, ++p)
1804 result *= power(*it, p);
1806 // Yun's algorithm does not account for constant factors. (For
1807 // univariate polynomials it works only in the monic case.) We can
1808 // correct this by inserting what has been lost back into the result:
1809 result = result * quo(tmp, result, x);
1810 return result * lcm.inverse();
1813 /** Compute square-free partial fraction decomposition of rational function
1816 * @param a rational function over Z[x], treated as univariate polynomial
1818 * @param x variable to factor in
1819 * @return decomposed rational function */
1820 ex sqrfree_parfrac(const ex & a, const symbol & x)
1822 // Find numerator and denominator
1823 ex nd = numer_denom(a);
1824 ex numer = nd.op(0), denom = nd.op(1);
1825 //clog << "numer = " << numer << ", denom = " << denom << endl;
1827 // Convert N(x)/D(x) -> Q(x) + R(x)/D(x), so degree(R) < degree(D)
1828 ex red_poly = quo(numer, denom, x), red_numer = rem(numer, denom, x).expand();
1829 //clog << "red_poly = " << red_poly << ", red_numer = " << red_numer << endl;
1831 // Factorize denominator and compute cofactors
1832 exvector yun = sqrfree_yun(denom, x);
1833 //clog << "yun factors: " << exprseq(yun) << endl;
1834 unsigned num_yun = yun.size();
1835 exvector factor; factor.reserve(num_yun);
1836 exvector cofac; cofac.reserve(num_yun);
1837 for (unsigned i=0; i<num_yun; i++) {
1838 if (!yun[i].is_equal(_ex1())) {
1839 for (unsigned j=0; j<=i; j++) {
1840 factor.push_back(pow(yun[i], j+1));
1842 for (unsigned k=0; k<num_yun; k++) {
1844 prod *= pow(yun[k], i-j);
1846 prod *= pow(yun[k], k+1);
1848 cofac.push_back(prod.expand());
1852 unsigned num_factors = factor.size();
1853 //clog << "factors : " << exprseq(factor) << endl;
1854 //clog << "cofactors: " << exprseq(cofac) << endl;
1856 // Construct coefficient matrix for decomposition
1857 int max_denom_deg = denom.degree(x);
1858 matrix sys(max_denom_deg + 1, num_factors);
1859 matrix rhs(max_denom_deg + 1, 1);
1860 for (int i=0; i<=max_denom_deg; i++) {
1861 for (unsigned j=0; j<num_factors; j++)
1862 sys(i, j) = cofac[j].coeff(x, i);
1863 rhs(i, 0) = red_numer.coeff(x, i);
1865 //clog << "coeffs: " << sys << endl;
1866 //clog << "rhs : " << rhs << endl;
1868 // Solve resulting linear system
1869 matrix vars(num_factors, 1);
1870 for (unsigned i=0; i<num_factors; i++)
1871 vars(i, 0) = symbol();
1872 matrix sol = sys.solve(vars, rhs);
1874 // Sum up decomposed fractions
1876 for (unsigned i=0; i<num_factors; i++)
1877 sum += sol(i, 0) / factor[i];
1879 return red_poly + sum;
1884 * Normal form of rational functions
1888 * Note: The internal normal() functions (= basic::normal() and overloaded
1889 * functions) all return lists of the form {numerator, denominator}. This
1890 * is to get around mul::eval()'s automatic expansion of numeric coefficients.
1891 * E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
1892 * the information that (a+b) is the numerator and 3 is the denominator.
1896 /** Create a symbol for replacing the expression "e" (or return a previously
1897 * assigned symbol). The symbol is appended to sym_lst and returned, the
1898 * expression is appended to repl_lst.
1899 * @see ex::normal */
1900 static ex replace_with_symbol(const ex &e, lst &sym_lst, lst &repl_lst)
1902 // Expression already in repl_lst? Then return the assigned symbol
1903 for (unsigned i=0; i<repl_lst.nops(); i++)
1904 if (repl_lst.op(i).is_equal(e))
1905 return sym_lst.op(i);
1907 // Otherwise create new symbol and add to list, taking care that the
1908 // replacement expression doesn't contain symbols from the sym_lst
1909 // because subs() is not recursive
1912 ex e_replaced = e.subs(sym_lst, repl_lst);
1914 repl_lst.append(e_replaced);
1918 /** Create a symbol for replacing the expression "e" (or return a previously
1919 * assigned symbol). An expression of the form "symbol == expression" is added
1920 * to repl_lst and the symbol is returned.
1921 * @see ex::to_rational */
1922 static ex replace_with_symbol(const ex &e, lst &repl_lst)
1924 // Expression already in repl_lst? Then return the assigned symbol
1925 for (unsigned i=0; i<repl_lst.nops(); i++)
1926 if (repl_lst.op(i).op(1).is_equal(e))
1927 return repl_lst.op(i).op(0);
1929 // Otherwise create new symbol and add to list, taking care that the
1930 // replacement expression doesn't contain symbols from the sym_lst
1931 // because subs() is not recursive
1934 ex e_replaced = e.subs(repl_lst);
1935 repl_lst.append(es == e_replaced);
1940 /** Function object to be applied by basic::normal(). */
1941 struct normal_map_function : public map_function {
1943 normal_map_function(int l) : level(l) {}
1944 ex operator()(const ex & e) { return normal(e, level); }
1947 /** Default implementation of ex::normal(). It normalizes the children and
1948 * replaces the object with a temporary symbol.
1949 * @see ex::normal */
1950 ex basic::normal(lst &sym_lst, lst &repl_lst, int level) const
1953 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1956 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1957 else if (level == -max_recursion_level)
1958 throw(std::runtime_error("max recursion level reached"));
1960 normal_map_function map_normal(level - 1);
1961 return (new lst(replace_with_symbol(map(map_normal), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1967 /** Implementation of ex::normal() for symbols. This returns the unmodified symbol.
1968 * @see ex::normal */
1969 ex symbol::normal(lst &sym_lst, lst &repl_lst, int level) const
1971 return (new lst(*this, _ex1()))->setflag(status_flags::dynallocated);
1975 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1976 * into re+I*im and replaces I and non-rational real numbers with a temporary
1978 * @see ex::normal */
1979 ex numeric::normal(lst &sym_lst, lst &repl_lst, int level) const
1981 numeric num = numer();
1984 if (num.is_real()) {
1985 if (!num.is_integer())
1986 numex = replace_with_symbol(numex, sym_lst, repl_lst);
1988 numeric re = num.real(), im = num.imag();
1989 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, sym_lst, repl_lst);
1990 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, sym_lst, repl_lst);
1991 numex = re_ex + im_ex * replace_with_symbol(I, sym_lst, repl_lst);
1994 // Denominator is always a real integer (see numeric::denom())
1995 return (new lst(numex, denom()))->setflag(status_flags::dynallocated);
1999 /** Fraction cancellation.
2000 * @param n numerator
2001 * @param d denominator
2002 * @return cancelled fraction {n, d} as a list */
2003 static ex frac_cancel(const ex &n, const ex &d)
2007 numeric pre_factor = _num1();
2009 //std::clog << "frac_cancel num = " << num << ", den = " << den << std::endl;
2011 // Handle trivial case where denominator is 1
2012 if (den.is_equal(_ex1()))
2013 return (new lst(num, den))->setflag(status_flags::dynallocated);
2015 // Handle special cases where numerator or denominator is 0
2017 return (new lst(num, _ex1()))->setflag(status_flags::dynallocated);
2018 if (den.expand().is_zero())
2019 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
2021 // Bring numerator and denominator to Z[X] by multiplying with
2022 // LCM of all coefficients' denominators
2023 numeric num_lcm = lcm_of_coefficients_denominators(num);
2024 numeric den_lcm = lcm_of_coefficients_denominators(den);
2025 num = multiply_lcm(num, num_lcm);
2026 den = multiply_lcm(den, den_lcm);
2027 pre_factor = den_lcm / num_lcm;
2029 // Cancel GCD from numerator and denominator
2031 if (gcd(num, den, &cnum, &cden, false) != _ex1()) {
2036 // Make denominator unit normal (i.e. coefficient of first symbol
2037 // as defined by get_first_symbol() is made positive)
2039 if (get_first_symbol(den, x)) {
2040 GINAC_ASSERT(is_ex_exactly_of_type(den.unit(*x),numeric));
2041 if (ex_to<numeric>(den.unit(*x)).is_negative()) {
2047 // Return result as list
2048 //std::clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << std::endl;
2049 return (new lst(num * pre_factor.numer(), den * pre_factor.denom()))->setflag(status_flags::dynallocated);
2053 /** Implementation of ex::normal() for a sum. It expands terms and performs
2054 * fractional addition.
2055 * @see ex::normal */
2056 ex add::normal(lst &sym_lst, lst &repl_lst, int level) const
2059 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
2060 else if (level == -max_recursion_level)
2061 throw(std::runtime_error("max recursion level reached"));
2063 // Normalize children and split each one into numerator and denominator
2064 exvector nums, dens;
2065 nums.reserve(seq.size()+1);
2066 dens.reserve(seq.size()+1);
2067 epvector::const_iterator it = seq.begin(), itend = seq.end();
2068 while (it != itend) {
2069 ex n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1);
2070 nums.push_back(n.op(0));
2071 dens.push_back(n.op(1));
2074 ex n = overall_coeff.bp->normal(sym_lst, repl_lst, level-1);
2075 nums.push_back(n.op(0));
2076 dens.push_back(n.op(1));
2077 GINAC_ASSERT(nums.size() == dens.size());
2079 // Now, nums is a vector of all numerators and dens is a vector of
2081 //std::clog << "add::normal uses " << nums.size() << " summands:\n";
2083 // Add fractions sequentially
2084 exvector::const_iterator num_it = nums.begin(), num_itend = nums.end();
2085 exvector::const_iterator den_it = dens.begin(), den_itend = dens.end();
2086 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
2087 ex num = *num_it++, den = *den_it++;
2088 while (num_it != num_itend) {
2089 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
2090 ex next_num = *num_it++, next_den = *den_it++;
2092 // Trivially add sequences of fractions with identical denominators
2093 while ((den_it != den_itend) && next_den.is_equal(*den_it)) {
2094 next_num += *num_it;
2098 // Additiion of two fractions, taking advantage of the fact that
2099 // the heuristic GCD algorithm computes the cofactors at no extra cost
2100 ex co_den1, co_den2;
2101 ex g = gcd(den, next_den, &co_den1, &co_den2, false);
2102 num = ((num * co_den2) + (next_num * co_den1)).expand();
2103 den *= co_den2; // this is the lcm(den, next_den)
2105 //std::clog << " common denominator = " << den << std::endl;
2107 // Cancel common factors from num/den
2108 return frac_cancel(num, den);
2112 /** Implementation of ex::normal() for a product. It cancels common factors
2114 * @see ex::normal() */
2115 ex mul::normal(lst &sym_lst, lst &repl_lst, int level) const
2118 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
2119 else if (level == -max_recursion_level)
2120 throw(std::runtime_error("max recursion level reached"));
2122 // Normalize children, separate into numerator and denominator
2123 exvector num; num.reserve(seq.size());
2124 exvector den; den.reserve(seq.size());
2126 epvector::const_iterator it = seq.begin(), itend = seq.end();
2127 while (it != itend) {
2128 n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1);
2129 num.push_back(n.op(0));
2130 den.push_back(n.op(1));
2133 n = overall_coeff.bp->normal(sym_lst, repl_lst, level-1);
2134 num.push_back(n.op(0));
2135 den.push_back(n.op(1));
2137 // Perform fraction cancellation
2138 return frac_cancel((new mul(num))->setflag(status_flags::dynallocated),
2139 (new mul(den))->setflag(status_flags::dynallocated));
2143 /** Implementation of ex::normal() for powers. It normalizes the basis,
2144 * distributes integer exponents to numerator and denominator, and replaces
2145 * non-integer powers by temporary symbols.
2146 * @see ex::normal */
2147 ex power::normal(lst &sym_lst, lst &repl_lst, int level) const
2150 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
2151 else if (level == -max_recursion_level)
2152 throw(std::runtime_error("max recursion level reached"));
2154 // Normalize basis and exponent (exponent gets reassembled)
2155 ex n_basis = basis.bp->normal(sym_lst, repl_lst, level-1);
2156 ex n_exponent = exponent.bp->normal(sym_lst, repl_lst, level-1);
2157 n_exponent = n_exponent.op(0) / n_exponent.op(1);
2159 if (n_exponent.info(info_flags::integer)) {
2161 if (n_exponent.info(info_flags::positive)) {
2163 // (a/b)^n -> {a^n, b^n}
2164 return (new lst(power(n_basis.op(0), n_exponent), power(n_basis.op(1), n_exponent)))->setflag(status_flags::dynallocated);
2166 } else if (n_exponent.info(info_flags::negative)) {
2168 // (a/b)^-n -> {b^n, a^n}
2169 return (new lst(power(n_basis.op(1), -n_exponent), power(n_basis.op(0), -n_exponent)))->setflag(status_flags::dynallocated);
2174 if (n_exponent.info(info_flags::positive)) {
2176 // (a/b)^x -> {sym((a/b)^x), 1}
2177 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);
2179 } else if (n_exponent.info(info_flags::negative)) {
2181 if (n_basis.op(1).is_equal(_ex1())) {
2183 // a^-x -> {1, sym(a^x)}
2184 return (new lst(_ex1(), replace_with_symbol(power(n_basis.op(0), -n_exponent), sym_lst, repl_lst)))->setflag(status_flags::dynallocated);
2188 // (a/b)^-x -> {sym((b/a)^x), 1}
2189 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);
2192 } else { // n_exponent not numeric
2194 // (a/b)^x -> {sym((a/b)^x, 1}
2195 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);
2201 /** Implementation of ex::normal() for pseries. It normalizes each coefficient
2202 * and replaces the series by a temporary symbol.
2203 * @see ex::normal */
2204 ex pseries::normal(lst &sym_lst, lst &repl_lst, int level) const
2207 epvector::const_iterator i = seq.begin(), end = seq.end();
2209 ex restexp = i->rest.normal();
2210 if (!restexp.is_zero())
2211 newseq.push_back(expair(restexp, i->coeff));
2214 ex n = pseries(relational(var,point), newseq);
2215 return (new lst(replace_with_symbol(n, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
2219 /** Normalization of rational functions.
2220 * This function converts an expression to its normal form
2221 * "numerator/denominator", where numerator and denominator are (relatively
2222 * prime) polynomials. Any subexpressions which are not rational functions
2223 * (like non-rational numbers, non-integer powers or functions like sin(),
2224 * cos() etc.) are replaced by temporary symbols which are re-substituted by
2225 * the (normalized) subexpressions before normal() returns (this way, any
2226 * expression can be treated as a rational function). normal() is applied
2227 * recursively to arguments of functions etc.
2229 * @param level maximum depth of recursion
2230 * @return normalized expression */
2231 ex ex::normal(int level) const
2233 lst sym_lst, repl_lst;
2235 ex e = bp->normal(sym_lst, repl_lst, level);
2236 GINAC_ASSERT(is_ex_of_type(e, lst));
2238 // Re-insert replaced symbols
2239 if (sym_lst.nops() > 0)
2240 e = e.subs(sym_lst, repl_lst);
2242 // Convert {numerator, denominator} form back to fraction
2243 return e.op(0) / e.op(1);
2246 /** Get numerator of an expression. If the expression is not of the normal
2247 * form "numerator/denominator", it is first converted to this form and
2248 * then the numerator is returned.
2251 * @return numerator */
2252 ex ex::numer(void) const
2254 lst sym_lst, repl_lst;
2256 ex e = bp->normal(sym_lst, repl_lst, 0);
2257 GINAC_ASSERT(is_ex_of_type(e, lst));
2259 // Re-insert replaced symbols
2260 if (sym_lst.nops() > 0)
2261 return e.op(0).subs(sym_lst, repl_lst);
2266 /** Get denominator of an expression. If the expression is not of the normal
2267 * form "numerator/denominator", it is first converted to this form and
2268 * then the denominator is returned.
2271 * @return denominator */
2272 ex ex::denom(void) const
2274 lst sym_lst, repl_lst;
2276 ex e = bp->normal(sym_lst, repl_lst, 0);
2277 GINAC_ASSERT(is_ex_of_type(e, lst));
2279 // Re-insert replaced symbols
2280 if (sym_lst.nops() > 0)
2281 return e.op(1).subs(sym_lst, repl_lst);
2286 /** Get numerator and denominator of an expression. If the expresison is not
2287 * of the normal form "numerator/denominator", it is first converted to this
2288 * form and then a list [numerator, denominator] is returned.
2291 * @return a list [numerator, denominator] */
2292 ex ex::numer_denom(void) const
2294 lst sym_lst, repl_lst;
2296 ex e = bp->normal(sym_lst, repl_lst, 0);
2297 GINAC_ASSERT(is_ex_of_type(e, lst));
2299 // Re-insert replaced symbols
2300 if (sym_lst.nops() > 0)
2301 return e.subs(sym_lst, repl_lst);
2307 /** Default implementation of ex::to_rational(). It replaces the object with a
2309 * @see ex::to_rational */
2310 ex basic::to_rational(lst &repl_lst) const
2312 return replace_with_symbol(*this, repl_lst);
2316 /** Implementation of ex::to_rational() for symbols. This returns the
2317 * unmodified symbol.
2318 * @see ex::to_rational */
2319 ex symbol::to_rational(lst &repl_lst) const
2325 /** Implementation of ex::to_rational() for a numeric. It splits complex
2326 * numbers into re+I*im and replaces I and non-rational real numbers with a
2328 * @see ex::to_rational */
2329 ex numeric::to_rational(lst &repl_lst) const
2333 return replace_with_symbol(*this, repl_lst);
2335 numeric re = real();
2336 numeric im = imag();
2337 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl_lst);
2338 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl_lst);
2339 return re_ex + im_ex * replace_with_symbol(I, repl_lst);
2345 /** Implementation of ex::to_rational() for powers. It replaces non-integer
2346 * powers by temporary symbols.
2347 * @see ex::to_rational */
2348 ex power::to_rational(lst &repl_lst) const
2350 if (exponent.info(info_flags::integer))
2351 return power(basis.to_rational(repl_lst), exponent);
2353 return replace_with_symbol(*this, repl_lst);
2357 /** Implementation of ex::to_rational() for expairseqs.
2358 * @see ex::to_rational */
2359 ex expairseq::to_rational(lst &repl_lst) const
2362 s.reserve(seq.size());
2363 epvector::const_iterator i = seq.begin(), end = seq.end();
2365 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*i).to_rational(repl_lst)));
2368 ex oc = overall_coeff.to_rational(repl_lst);
2369 if (oc.info(info_flags::numeric))
2370 return thisexpairseq(s, overall_coeff);
2372 s.push_back(combine_ex_with_coeff_to_pair(oc, _ex1()));
2373 return thisexpairseq(s, default_overall_coeff());
2377 /** Rationalization of non-rational functions.
2378 * This function converts a general expression to a rational polynomial
2379 * by replacing all non-rational subexpressions (like non-rational numbers,
2380 * non-integer powers or functions like sin(), cos() etc.) to temporary
2381 * symbols. This makes it possible to use functions like gcd() and divide()
2382 * on non-rational functions by applying to_rational() on the arguments,
2383 * calling the desired function and re-substituting the temporary symbols
2384 * in the result. To make the last step possible, all temporary symbols and
2385 * their associated expressions are collected in the list specified by the
2386 * repl_lst parameter in the form {symbol == expression}, ready to be passed
2387 * as an argument to ex::subs().
2389 * @param repl_lst collects a list of all temporary symbols and their replacements
2390 * @return rationalized expression */
2391 ex ex::to_rational(lst &repl_lst) const
2393 return bp->to_rational(repl_lst);
2397 } // namespace GiNaC