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::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)) {
273 numeric lcm_accum = _num1();
274 for (unsigned i=0; i<e.nops(); i++) {
275 numeric op_lcm = lcmcoeff(e.op(i), _num1());
276 c *= multiply_lcm(e.op(i), op_lcm);
279 c *= lcm / lcm_accum;
281 } else if (is_ex_exactly_of_type(e, add)) {
283 for (unsigned i=0; i<e.nops(); i++)
284 c += multiply_lcm(e.op(i), lcm);
286 } else if (is_ex_exactly_of_type(e, power)) {
287 if (is_ex_exactly_of_type(e.op(0), symbol))
290 return pow(multiply_lcm(e.op(0), lcm.power(ex_to<numeric>(e.op(1)).inverse())), e.op(1));
296 /** Compute the integer content (= GCD of all numeric coefficients) of an
297 * expanded polynomial.
299 * @param e expanded polynomial
300 * @return integer content */
301 numeric ex::integer_content(void) const
304 return bp->integer_content();
307 numeric basic::integer_content(void) const
312 numeric numeric::integer_content(void) const
317 numeric add::integer_content(void) const
319 epvector::const_iterator it = seq.begin();
320 epvector::const_iterator itend = seq.end();
322 while (it != itend) {
323 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
324 GINAC_ASSERT(is_ex_exactly_of_type(it->coeff,numeric));
325 c = gcd(ex_to<numeric>(it->coeff), c);
328 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
329 c = gcd(ex_to<numeric>(overall_coeff),c);
333 numeric mul::integer_content(void) const
335 #ifdef DO_GINAC_ASSERT
336 epvector::const_iterator it = seq.begin();
337 epvector::const_iterator itend = seq.end();
338 while (it != itend) {
339 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
342 #endif // def DO_GINAC_ASSERT
343 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
344 return abs(ex_to<numeric>(overall_coeff));
349 * Polynomial quotients and remainders
352 /** Quotient q(x) of polynomials a(x) and b(x) in Q[x].
353 * It satisfies a(x)=b(x)*q(x)+r(x).
355 * @param a first polynomial in x (dividend)
356 * @param b second polynomial in x (divisor)
357 * @param x a and b are polynomials in x
358 * @param check_args check whether a and b are polynomials with rational
359 * coefficients (defaults to "true")
360 * @return quotient of a and b in Q[x] */
361 ex quo(const ex &a, const ex &b, const symbol &x, bool check_args)
364 throw(std::overflow_error("quo: division by zero"));
365 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
371 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
372 throw(std::invalid_argument("quo: arguments must be polynomials over the rationals"));
374 // Polynomial long division
379 int bdeg = b.degree(x);
380 int rdeg = r.degree(x);
381 ex blcoeff = b.expand().coeff(x, bdeg);
382 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
383 while (rdeg >= bdeg) {
384 ex term, rcoeff = r.coeff(x, rdeg);
385 if (blcoeff_is_numeric)
386 term = rcoeff / blcoeff;
388 if (!divide(rcoeff, blcoeff, term, false))
389 return (new fail())->setflag(status_flags::dynallocated);
391 term *= power(x, rdeg - bdeg);
393 r -= (term * b).expand();
402 /** Remainder r(x) of polynomials a(x) and b(x) in Q[x].
403 * It satisfies a(x)=b(x)*q(x)+r(x).
405 * @param a first polynomial in x (dividend)
406 * @param b second polynomial in x (divisor)
407 * @param x a and b are polynomials in x
408 * @param check_args check whether a and b are polynomials with rational
409 * coefficients (defaults to "true")
410 * @return remainder of a(x) and b(x) in Q[x] */
411 ex rem(const ex &a, const ex &b, const symbol &x, bool check_args)
414 throw(std::overflow_error("rem: division by zero"));
415 if (is_ex_exactly_of_type(a, numeric)) {
416 if (is_ex_exactly_of_type(b, numeric))
425 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
426 throw(std::invalid_argument("rem: arguments must be polynomials over the rationals"));
428 // Polynomial long division
432 int bdeg = b.degree(x);
433 int rdeg = r.degree(x);
434 ex blcoeff = b.expand().coeff(x, bdeg);
435 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
436 while (rdeg >= bdeg) {
437 ex term, rcoeff = r.coeff(x, rdeg);
438 if (blcoeff_is_numeric)
439 term = rcoeff / blcoeff;
441 if (!divide(rcoeff, blcoeff, term, false))
442 return (new fail())->setflag(status_flags::dynallocated);
444 term *= power(x, rdeg - bdeg);
445 r -= (term * b).expand();
454 /** Decompose rational function a(x)=N(x)/D(x) into P(x)+n(x)/D(x)
455 * with degree(n, x) < degree(D, x).
457 * @param a rational function in x
458 * @param x a is a function of x
459 * @return decomposed function. */
460 ex decomp_rational(const ex &a, const symbol &x)
462 ex nd = numer_denom(a);
463 ex numer = nd.op(0), denom = nd.op(1);
464 ex q = quo(numer, denom, x);
465 if (is_ex_exactly_of_type(q, fail))
468 return q + rem(numer, denom, x) / denom;
472 /** Pseudo-remainder of polynomials a(x) and b(x) in Z[x].
474 * @param a first polynomial in x (dividend)
475 * @param b second polynomial in x (divisor)
476 * @param x a and b are polynomials in x
477 * @param check_args check whether a and b are polynomials with rational
478 * coefficients (defaults to "true")
479 * @return pseudo-remainder of a(x) and b(x) in Z[x] */
480 ex prem(const ex &a, const ex &b, const symbol &x, bool check_args)
483 throw(std::overflow_error("prem: division by zero"));
484 if (is_ex_exactly_of_type(a, numeric)) {
485 if (is_ex_exactly_of_type(b, numeric))
490 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
491 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
493 // Polynomial long division
496 int rdeg = r.degree(x);
497 int bdeg = eb.degree(x);
500 blcoeff = eb.coeff(x, bdeg);
504 eb -= blcoeff * power(x, bdeg);
508 int delta = rdeg - bdeg + 1, i = 0;
509 while (rdeg >= bdeg && !r.is_zero()) {
510 ex rlcoeff = r.coeff(x, rdeg);
511 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
515 r -= rlcoeff * power(x, rdeg);
516 r = (blcoeff * r).expand() - term;
520 return power(blcoeff, delta - i) * r;
524 /** Sparse pseudo-remainder of polynomials a(x) and b(x) in Z[x].
526 * @param a first polynomial in x (dividend)
527 * @param b second polynomial in x (divisor)
528 * @param x a and b are polynomials in x
529 * @param check_args check whether a and b are polynomials with rational
530 * coefficients (defaults to "true")
531 * @return sparse pseudo-remainder of a(x) and b(x) in Z[x] */
533 ex sprem(const ex &a, const ex &b, const symbol &x, bool check_args)
536 throw(std::overflow_error("prem: division by zero"));
537 if (is_ex_exactly_of_type(a, numeric)) {
538 if (is_ex_exactly_of_type(b, numeric))
543 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
544 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
546 // Polynomial long division
549 int rdeg = r.degree(x);
550 int bdeg = eb.degree(x);
553 blcoeff = eb.coeff(x, bdeg);
557 eb -= blcoeff * power(x, bdeg);
561 while (rdeg >= bdeg && !r.is_zero()) {
562 ex rlcoeff = r.coeff(x, rdeg);
563 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
567 r -= rlcoeff * power(x, rdeg);
568 r = (blcoeff * r).expand() - term;
575 /** Exact polynomial division of a(X) by b(X) in Q[X].
577 * @param a first multivariate polynomial (dividend)
578 * @param b second multivariate polynomial (divisor)
579 * @param q quotient (returned)
580 * @param check_args check whether a and b are polynomials with rational
581 * coefficients (defaults to "true")
582 * @return "true" when exact division succeeds (quotient returned in q),
583 * "false" otherwise */
584 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
588 throw(std::overflow_error("divide: division by zero"));
591 if (is_ex_exactly_of_type(b, numeric)) {
594 } else if (is_ex_exactly_of_type(a, numeric))
602 if (check_args && (!a.info(info_flags::rational_polynomial) ||
603 !b.info(info_flags::rational_polynomial)))
604 throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
608 if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
609 throw(std::invalid_argument("invalid expression in divide()"));
611 // Polynomial long division (recursive)
615 int bdeg = b.degree(*x);
616 int rdeg = r.degree(*x);
617 ex blcoeff = b.expand().coeff(*x, bdeg);
618 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
619 while (rdeg >= bdeg) {
620 ex term, rcoeff = r.coeff(*x, rdeg);
621 if (blcoeff_is_numeric)
622 term = rcoeff / blcoeff;
624 if (!divide(rcoeff, blcoeff, term, false))
626 term *= power(*x, rdeg - bdeg);
628 r -= (term * b).expand();
642 typedef std::pair<ex, ex> ex2;
643 typedef std::pair<ex, bool> exbool;
646 bool operator() (const ex2 &p, const ex2 &q) const
648 int cmp = p.first.compare(q.first);
649 return ((cmp<0) || (!(cmp>0) && p.second.compare(q.second)<0));
653 typedef std::map<ex2, exbool, ex2_less> ex2_exbool_remember;
657 /** Exact polynomial division of a(X) by b(X) in Z[X].
658 * This functions works like divide() but the input and output polynomials are
659 * in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
660 * divide(), it doesnĀ“t check whether the input polynomials really are integer
661 * polynomials, so be careful of what you pass in. Also, you have to run
662 * get_symbol_stats() over the input polynomials before calling this function
663 * and pass an iterator to the first element of the sym_desc vector. This
664 * function is used internally by the heur_gcd().
666 * @param a first multivariate polynomial (dividend)
667 * @param b second multivariate polynomial (divisor)
668 * @param q quotient (returned)
669 * @param var iterator to first element of vector of sym_desc structs
670 * @return "true" when exact division succeeds (the quotient is returned in
671 * q), "false" otherwise.
672 * @see get_symbol_stats, heur_gcd */
673 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
677 throw(std::overflow_error("divide_in_z: division by zero"));
678 if (b.is_equal(_ex1())) {
682 if (is_ex_exactly_of_type(a, numeric)) {
683 if (is_ex_exactly_of_type(b, numeric)) {
685 return q.info(info_flags::integer);
698 static ex2_exbool_remember dr_remember;
699 ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
700 if (remembered != dr_remember.end()) {
701 q = remembered->second.first;
702 return remembered->second.second;
707 const symbol *x = var->sym;
710 int adeg = a.degree(*x), bdeg = b.degree(*x);
714 #if USE_TRIAL_DIVISION
716 // Trial division with polynomial interpolation
719 // Compute values at evaluation points 0..adeg
720 vector<numeric> alpha; alpha.reserve(adeg + 1);
721 exvector u; u.reserve(adeg + 1);
722 numeric point = _num0();
724 for (i=0; i<=adeg; i++) {
725 ex bs = b.subs(*x == point);
726 while (bs.is_zero()) {
728 bs = b.subs(*x == point);
730 if (!divide_in_z(a.subs(*x == point), bs, c, var+1))
732 alpha.push_back(point);
738 vector<numeric> rcp; rcp.reserve(adeg + 1);
739 rcp.push_back(_num0());
740 for (k=1; k<=adeg; k++) {
741 numeric product = alpha[k] - alpha[0];
743 product *= alpha[k] - alpha[i];
744 rcp.push_back(product.inverse());
747 // Compute Newton coefficients
748 exvector v; v.reserve(adeg + 1);
750 for (k=1; k<=adeg; k++) {
752 for (i=k-2; i>=0; i--)
753 temp = temp * (alpha[k] - alpha[i]) + v[i];
754 v.push_back((u[k] - temp) * rcp[k]);
757 // Convert from Newton form to standard form
759 for (k=adeg-1; k>=0; k--)
760 c = c * (*x - alpha[k]) + v[k];
762 if (c.degree(*x) == (adeg - bdeg)) {
770 // Polynomial long division (recursive)
776 ex blcoeff = eb.coeff(*x, bdeg);
777 while (rdeg >= bdeg) {
778 ex term, rcoeff = r.coeff(*x, rdeg);
779 if (!divide_in_z(rcoeff, blcoeff, term, var+1))
781 term = (term * power(*x, rdeg - bdeg)).expand();
783 r -= (term * eb).expand();
786 dr_remember[ex2(a, b)] = exbool(q, true);
793 dr_remember[ex2(a, b)] = exbool(q, false);
802 * Separation of unit part, content part and primitive part of polynomials
805 /** Compute unit part (= sign of leading coefficient) of a multivariate
806 * polynomial in Z[x]. The product of unit part, content part, and primitive
807 * part is the polynomial itself.
809 * @param x variable in which to compute the unit part
811 * @see ex::content, ex::primpart */
812 ex ex::unit(const symbol &x) const
814 ex c = expand().lcoeff(x);
815 if (is_ex_exactly_of_type(c, numeric))
816 return c < _ex0() ? _ex_1() : _ex1();
819 if (get_first_symbol(c, y))
822 throw(std::invalid_argument("invalid expression in unit()"));
827 /** Compute content part (= unit normal GCD of all coefficients) of a
828 * multivariate polynomial in Z[x]. The product of unit part, content part,
829 * and primitive part is the polynomial itself.
831 * @param x variable in which to compute the content part
832 * @return content part
833 * @see ex::unit, ex::primpart */
834 ex ex::content(const symbol &x) const
838 if (is_ex_exactly_of_type(*this, numeric))
839 return info(info_flags::negative) ? -*this : *this;
844 // First, try the integer content
845 ex c = e.integer_content();
847 ex lcoeff = r.lcoeff(x);
848 if (lcoeff.info(info_flags::integer))
851 // GCD of all coefficients
852 int deg = e.degree(x);
853 int ldeg = e.ldegree(x);
855 return e.lcoeff(x) / e.unit(x);
857 for (int i=ldeg; i<=deg; i++)
858 c = gcd(e.coeff(x, i), c, NULL, NULL, false);
863 /** Compute primitive part of a multivariate polynomial in Z[x].
864 * The product of unit part, content part, and primitive part is the
867 * @param x variable in which to compute the primitive part
868 * @return primitive part
869 * @see ex::unit, ex::content */
870 ex ex::primpart(const symbol &x) const
874 if (is_ex_exactly_of_type(*this, numeric))
881 if (is_ex_exactly_of_type(c, numeric))
882 return *this / (c * u);
884 return quo(*this, c * u, x, false);
888 /** Compute primitive part of a multivariate polynomial in Z[x] when the
889 * content part is already known. This function is faster in computing the
890 * primitive part than the previous function.
892 * @param x variable in which to compute the primitive part
893 * @param c previously computed content part
894 * @return primitive part */
895 ex ex::primpart(const symbol &x, const ex &c) const
901 if (is_ex_exactly_of_type(*this, numeric))
905 if (is_ex_exactly_of_type(c, numeric))
906 return *this / (c * u);
908 return quo(*this, c * u, x, false);
913 * GCD of multivariate polynomials
916 /** Compute GCD of polynomials in Q[X] using the Euclidean algorithm (not
917 * really suited for multivariate GCDs). This function is only provided for
920 * @param a first multivariate polynomial
921 * @param b second multivariate polynomial
922 * @param x pointer to symbol (main variable) in which to compute the GCD in
923 * @return the GCD as a new expression
926 static ex eu_gcd(const ex &a, const ex &b, const symbol *x)
928 //std::clog << "eu_gcd(" << a << "," << b << ")\n";
930 // Sort c and d so that c has higher degree
932 int adeg = a.degree(*x), bdeg = b.degree(*x);
942 c = c / c.lcoeff(*x);
943 d = d / d.lcoeff(*x);
945 // Euclidean algorithm
948 //std::clog << " d = " << d << endl;
949 r = rem(c, d, *x, false);
951 return d / d.lcoeff(*x);
958 /** Compute GCD of multivariate polynomials using the Euclidean PRS algorithm
959 * with pseudo-remainders ("World's Worst GCD Algorithm", staying in Z[X]).
960 * This function is only provided for testing purposes.
962 * @param a first multivariate polynomial
963 * @param b second multivariate polynomial
964 * @param x pointer to symbol (main variable) in which to compute the GCD in
965 * @return the GCD as a new expression
968 static ex euprem_gcd(const ex &a, const ex &b, const symbol *x)
970 //std::clog << "euprem_gcd(" << a << "," << b << ")\n";
972 // Sort c and d so that c has higher degree
974 int adeg = a.degree(*x), bdeg = b.degree(*x);
983 // Calculate GCD of contents
984 ex gamma = gcd(c.content(*x), d.content(*x), NULL, NULL, false);
986 // Euclidean algorithm with pseudo-remainders
989 //std::clog << " d = " << d << endl;
990 r = prem(c, d, *x, false);
992 return d.primpart(*x) * gamma;
999 /** Compute GCD of multivariate polynomials using the primitive Euclidean
1000 * PRS algorithm (complete content removal at each step). This function is
1001 * only provided for testing purposes.
1003 * @param a first multivariate polynomial
1004 * @param b second multivariate polynomial
1005 * @param x pointer to symbol (main variable) in which to compute the GCD in
1006 * @return the GCD as a new expression
1009 static ex peu_gcd(const ex &a, const ex &b, const symbol *x)
1011 //std::clog << "peu_gcd(" << a << "," << b << ")\n";
1013 // Sort c and d so that c has higher degree
1015 int adeg = a.degree(*x), bdeg = b.degree(*x);
1027 // Remove content from c and d, to be attached to GCD later
1028 ex cont_c = c.content(*x);
1029 ex cont_d = d.content(*x);
1030 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1033 c = c.primpart(*x, cont_c);
1034 d = d.primpart(*x, cont_d);
1036 // Euclidean algorithm with content removal
1039 //std::clog << " d = " << d << endl;
1040 r = prem(c, d, *x, false);
1049 /** Compute GCD of multivariate polynomials using the reduced PRS algorithm.
1050 * This function is only provided for testing purposes.
1052 * @param a first multivariate polynomial
1053 * @param b second multivariate polynomial
1054 * @param x pointer to symbol (main variable) in which to compute the GCD in
1055 * @return the GCD as a new expression
1058 static ex red_gcd(const ex &a, const ex &b, const symbol *x)
1060 //std::clog << "red_gcd(" << a << "," << b << ")\n";
1062 // Sort c and d so that c has higher degree
1064 int adeg = a.degree(*x), bdeg = b.degree(*x);
1078 // Remove content from c and d, to be attached to GCD later
1079 ex cont_c = c.content(*x);
1080 ex cont_d = d.content(*x);
1081 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1084 c = c.primpart(*x, cont_c);
1085 d = d.primpart(*x, cont_d);
1087 // First element of divisor sequence
1089 int delta = cdeg - ddeg;
1092 // Calculate polynomial pseudo-remainder
1093 //std::clog << " d = " << d << endl;
1094 r = prem(c, d, *x, false);
1096 return gamma * d.primpart(*x);
1100 if (!divide(r, pow(ri, delta), d, false))
1101 throw(std::runtime_error("invalid expression in red_gcd(), division failed"));
1102 ddeg = d.degree(*x);
1104 if (is_ex_exactly_of_type(r, numeric))
1107 return gamma * r.primpart(*x);
1110 ri = c.expand().lcoeff(*x);
1111 delta = cdeg - ddeg;
1116 /** Compute GCD of multivariate polynomials using the subresultant PRS
1117 * algorithm. This function is used internally by gcd().
1119 * @param a first multivariate polynomial
1120 * @param b second multivariate polynomial
1121 * @param var iterator to first element of vector of sym_desc structs
1122 * @return the GCD as a new expression
1125 static ex sr_gcd(const ex &a, const ex &b, sym_desc_vec::const_iterator var)
1127 //std::clog << "sr_gcd(" << a << "," << b << ")\n";
1132 // The first symbol is our main variable
1133 const symbol &x = *(var->sym);
1135 // Sort c and d so that c has higher degree
1137 int adeg = a.degree(x), bdeg = b.degree(x);
1151 // Remove content from c and d, to be attached to GCD later
1152 ex cont_c = c.content(x);
1153 ex cont_d = d.content(x);
1154 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1157 c = c.primpart(x, cont_c);
1158 d = d.primpart(x, cont_d);
1159 //std::clog << " content " << gamma << " removed, continuing with sr_gcd(" << c << "," << d << ")\n";
1161 // First element of subresultant sequence
1162 ex r = _ex0(), ri = _ex1(), psi = _ex1();
1163 int delta = cdeg - ddeg;
1166 // Calculate polynomial pseudo-remainder
1167 //std::clog << " start of loop, psi = " << psi << ", calculating pseudo-remainder...\n";
1168 //std::clog << " d = " << d << endl;
1169 r = prem(c, d, x, false);
1171 return gamma * d.primpart(x);
1174 //std::clog << " dividing...\n";
1175 if (!divide_in_z(r, ri * pow(psi, delta), d, var))
1176 throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
1179 if (is_ex_exactly_of_type(r, numeric))
1182 return gamma * r.primpart(x);
1185 // Next element of subresultant sequence
1186 //std::clog << " calculating next subresultant...\n";
1187 ri = c.expand().lcoeff(x);
1191 divide_in_z(pow(ri, delta), pow(psi, delta-1), psi, var+1);
1192 delta = cdeg - ddeg;
1197 /** Return maximum (absolute value) coefficient of a polynomial.
1198 * This function is used internally by heur_gcd().
1200 * @param e expanded multivariate polynomial
1201 * @return maximum coefficient
1203 numeric ex::max_coefficient(void) const
1205 GINAC_ASSERT(bp!=0);
1206 return bp->max_coefficient();
1209 /** Implementation ex::max_coefficient().
1211 numeric basic::max_coefficient(void) const
1216 numeric numeric::max_coefficient(void) const
1221 numeric add::max_coefficient(void) const
1223 epvector::const_iterator it = seq.begin();
1224 epvector::const_iterator itend = seq.end();
1225 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1226 numeric cur_max = abs(ex_to<numeric>(overall_coeff));
1227 while (it != itend) {
1229 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
1230 a = abs(ex_to<numeric>(it->coeff));
1238 numeric mul::max_coefficient(void) const
1240 #ifdef DO_GINAC_ASSERT
1241 epvector::const_iterator it = seq.begin();
1242 epvector::const_iterator itend = seq.end();
1243 while (it != itend) {
1244 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
1247 #endif // def DO_GINAC_ASSERT
1248 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1249 return abs(ex_to<numeric>(overall_coeff));
1253 /** Apply symmetric modular homomorphism to a multivariate polynomial.
1254 * This function is used internally by heur_gcd().
1256 * @param e expanded multivariate polynomial
1258 * @return mapped polynomial
1260 ex ex::smod(const numeric &xi) const
1262 GINAC_ASSERT(bp!=0);
1263 return bp->smod(xi);
1266 ex basic::smod(const numeric &xi) const
1271 ex numeric::smod(const numeric &xi) const
1273 return GiNaC::smod(*this, xi);
1276 ex add::smod(const numeric &xi) const
1279 newseq.reserve(seq.size()+1);
1280 epvector::const_iterator it = seq.begin();
1281 epvector::const_iterator itend = seq.end();
1282 while (it != itend) {
1283 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
1284 numeric coeff = GiNaC::smod(ex_to<numeric>(it->coeff), xi);
1285 if (!coeff.is_zero())
1286 newseq.push_back(expair(it->rest, coeff));
1289 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1290 numeric coeff = GiNaC::smod(ex_to<numeric>(overall_coeff), xi);
1291 return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
1294 ex mul::smod(const numeric &xi) const
1296 #ifdef DO_GINAC_ASSERT
1297 epvector::const_iterator it = seq.begin();
1298 epvector::const_iterator itend = seq.end();
1299 while (it != itend) {
1300 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
1303 #endif // def DO_GINAC_ASSERT
1304 mul * mulcopyp = new mul(*this);
1305 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1306 mulcopyp->overall_coeff = GiNaC::smod(ex_to<numeric>(overall_coeff),xi);
1307 mulcopyp->clearflag(status_flags::evaluated);
1308 mulcopyp->clearflag(status_flags::hash_calculated);
1309 return mulcopyp->setflag(status_flags::dynallocated);
1313 /** xi-adic polynomial interpolation */
1314 static ex interpolate(const ex &gamma, const numeric &xi, const symbol &x)
1318 numeric rxi = xi.inverse();
1319 for (int i=0; !e.is_zero(); i++) {
1321 g += gi * power(x, i);
1327 /** Exception thrown by heur_gcd() to signal failure. */
1328 class gcdheu_failed {};
1330 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1331 * get_symbol_stats() must have been called previously with the input
1332 * polynomials and an iterator to the first element of the sym_desc vector
1333 * passed in. This function is used internally by gcd().
1335 * @param a first multivariate polynomial (expanded)
1336 * @param b second multivariate polynomial (expanded)
1337 * @param ca cofactor of polynomial a (returned), NULL to suppress
1338 * calculation of cofactor
1339 * @param cb cofactor of polynomial b (returned), NULL to suppress
1340 * calculation of cofactor
1341 * @param var iterator to first element of vector of sym_desc structs
1342 * @return the GCD as a new expression
1344 * @exception gcdheu_failed() */
1345 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
1347 //std::clog << "heur_gcd(" << a << "," << b << ")\n";
1352 // Algorithms only works for non-vanishing input polynomials
1353 if (a.is_zero() || b.is_zero())
1354 return (new fail())->setflag(status_flags::dynallocated);
1356 // GCD of two numeric values -> CLN
1357 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1358 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1360 *ca = ex_to<numeric>(a) / g;
1362 *cb = ex_to<numeric>(b) / g;
1366 // The first symbol is our main variable
1367 const symbol &x = *(var->sym);
1369 // Remove integer content
1370 numeric gc = gcd(a.integer_content(), b.integer_content());
1371 numeric rgc = gc.inverse();
1374 int maxdeg = std::max(p.degree(x),q.degree(x));
1376 // Find evaluation point
1377 numeric mp = p.max_coefficient();
1378 numeric mq = q.max_coefficient();
1381 xi = mq * _num2() + _num2();
1383 xi = mp * _num2() + _num2();
1386 for (int t=0; t<6; t++) {
1387 if (xi.int_length() * maxdeg > 100000) {
1388 //std::clog << "giving up heur_gcd, xi.int_length = " << xi.int_length() << ", maxdeg = " << maxdeg << std::endl;
1389 throw gcdheu_failed();
1392 // Apply evaluation homomorphism and calculate GCD
1394 ex gamma = heur_gcd(p.subs(x == xi), q.subs(x == xi), &cp, &cq, var+1).expand();
1395 if (!is_ex_exactly_of_type(gamma, fail)) {
1397 // Reconstruct polynomial from GCD of mapped polynomials
1398 ex g = interpolate(gamma, xi, x);
1400 // Remove integer content
1401 g /= g.integer_content();
1403 // If the calculated polynomial divides both p and q, this is the GCD
1405 if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1407 ex lc = g.lcoeff(x);
1408 if (is_ex_exactly_of_type(lc, numeric) && ex_to<numeric>(lc).is_negative())
1414 cp = interpolate(cp, xi, x);
1415 if (divide_in_z(cp, p, g, var)) {
1416 if (divide_in_z(g, q, cb ? *cb : dummy, var)) {
1420 ex lc = g.lcoeff(x);
1421 if (is_ex_exactly_of_type(lc, numeric) && ex_to<numeric>(lc).is_negative())
1427 cq = interpolate(cq, xi, x);
1428 if (divide_in_z(cq, q, g, var)) {
1429 if (divide_in_z(g, p, ca ? *ca : dummy, var)) {
1433 ex lc = g.lcoeff(x);
1434 if (is_ex_exactly_of_type(lc, numeric) && ex_to<numeric>(lc).is_negative())
1443 // Next evaluation point
1444 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1446 return (new fail())->setflag(status_flags::dynallocated);
1450 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1453 * @param a first multivariate polynomial
1454 * @param b second multivariate polynomial
1455 * @param check_args check whether a and b are polynomials with rational
1456 * coefficients (defaults to "true")
1457 * @return the GCD as a new expression */
1458 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1460 //std::clog << "gcd(" << a << "," << b << ")\n";
1465 // GCD of numerics -> CLN
1466 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1467 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1476 *ca = ex_to<numeric>(a) / g;
1478 *cb = ex_to<numeric>(b) / g;
1485 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))) {
1486 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1489 // Partially factored cases (to avoid expanding large expressions)
1490 if (is_ex_exactly_of_type(a, mul)) {
1491 if (is_ex_exactly_of_type(b, mul) && b.nops() > a.nops())
1497 for (unsigned i=0; i<a.nops(); i++) {
1498 ex part_ca, part_cb;
1499 g *= gcd(a.op(i), part_b, &part_ca, &part_cb, check_args);
1508 } else if (is_ex_exactly_of_type(b, mul)) {
1509 if (is_ex_exactly_of_type(a, mul) && a.nops() > b.nops())
1515 for (unsigned i=0; i<b.nops(); i++) {
1516 ex part_ca, part_cb;
1517 g *= gcd(part_a, b.op(i), &part_ca, &part_cb, check_args);
1529 // Input polynomials of the form poly^n are sometimes also trivial
1530 if (is_ex_exactly_of_type(a, power)) {
1532 if (is_ex_exactly_of_type(b, power)) {
1533 if (p.is_equal(b.op(0))) {
1534 // a = p^n, b = p^m, gcd = p^min(n, m)
1535 ex exp_a = a.op(1), exp_b = b.op(1);
1536 if (exp_a < exp_b) {
1540 *cb = power(p, exp_b - exp_a);
1541 return power(p, exp_a);
1544 *ca = power(p, exp_a - exp_b);
1547 return power(p, exp_b);
1551 if (p.is_equal(b)) {
1552 // a = p^n, b = p, gcd = p
1554 *ca = power(p, a.op(1) - 1);
1560 } else if (is_ex_exactly_of_type(b, power)) {
1562 if (p.is_equal(a)) {
1563 // a = p, b = p^n, gcd = p
1567 *cb = power(p, b.op(1) - 1);
1573 // Some trivial cases
1574 ex aex = a.expand(), bex = b.expand();
1575 if (aex.is_zero()) {
1582 if (bex.is_zero()) {
1589 if (aex.is_equal(_ex1()) || bex.is_equal(_ex1())) {
1597 if (a.is_equal(b)) {
1606 // Gather symbol statistics
1607 sym_desc_vec sym_stats;
1608 get_symbol_stats(a, b, sym_stats);
1610 // The symbol with least degree is our main variable
1611 sym_desc_vec::const_iterator var = sym_stats.begin();
1612 const symbol &x = *(var->sym);
1614 // Cancel trivial common factor
1615 int ldeg_a = var->ldeg_a;
1616 int ldeg_b = var->ldeg_b;
1617 int min_ldeg = std::min(ldeg_a,ldeg_b);
1619 ex common = power(x, min_ldeg);
1620 //std::clog << "trivial common factor " << common << std::endl;
1621 return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1624 // Try to eliminate variables
1625 if (var->deg_a == 0) {
1626 //std::clog << "eliminating variable " << x << " from b" << std::endl;
1627 ex c = bex.content(x);
1628 ex g = gcd(aex, c, ca, cb, false);
1630 *cb *= bex.unit(x) * bex.primpart(x, c);
1632 } else if (var->deg_b == 0) {
1633 //std::clog << "eliminating variable " << x << " from a" << std::endl;
1634 ex c = aex.content(x);
1635 ex g = gcd(c, bex, ca, cb, false);
1637 *ca *= aex.unit(x) * aex.primpart(x, c);
1643 // Try heuristic algorithm first, fall back to PRS if that failed
1645 g = heur_gcd(aex, bex, ca, cb, var);
1646 } catch (gcdheu_failed) {
1649 if (is_ex_exactly_of_type(g, fail)) {
1650 //std::clog << "heuristics failed" << std::endl;
1655 // g = heur_gcd(aex, bex, ca, cb, var);
1656 // g = eu_gcd(aex, bex, &x);
1657 // g = euprem_gcd(aex, bex, &x);
1658 // g = peu_gcd(aex, bex, &x);
1659 // g = red_gcd(aex, bex, &x);
1660 g = sr_gcd(aex, bex, var);
1661 if (g.is_equal(_ex1())) {
1662 // Keep cofactors factored if possible
1669 divide(aex, g, *ca, false);
1671 divide(bex, g, *cb, false);
1675 if (g.is_equal(_ex1())) {
1676 // Keep cofactors factored if possible
1688 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1690 * @param a first multivariate polynomial
1691 * @param b second multivariate polynomial
1692 * @param check_args check whether a and b are polynomials with rational
1693 * coefficients (defaults to "true")
1694 * @return the LCM as a new expression */
1695 ex lcm(const ex &a, const ex &b, bool check_args)
1697 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
1698 return lcm(ex_to<numeric>(a), ex_to<numeric>(b));
1699 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
1700 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1703 ex g = gcd(a, b, &ca, &cb, false);
1709 * Square-free factorization
1712 /** Compute square-free factorization of multivariate polynomial a(x) using
1713 * YunĀ“s algorithm. Used internally by sqrfree().
1715 * @param a multivariate polynomial over Z[X], treated here as univariate
1717 * @param x variable to factor in
1718 * @return vector of factors sorted in ascending degree */
1719 static exvector sqrfree_yun(const ex &a, const symbol &x)
1725 if (g.is_equal(_ex1())) {
1736 } while (!z.is_zero());
1740 /** Compute square-free factorization of multivariate polynomial in Q[X].
1742 * @param a multivariate polynomial over Q[X]
1743 * @param x lst of variables to factor in, may be left empty for autodetection
1744 * @return polynomail a in square-free factored form. */
1745 ex sqrfree(const ex &a, const lst &l)
1747 if (is_ex_of_type(a,numeric) || // algorithm does not trap a==0
1748 is_ex_of_type(a,symbol)) // shortcut
1750 // If no lst of variables to factorize in was specified we have to
1751 // invent one now. Maybe one can optimize here by reversing the order
1752 // or so, I don't know.
1756 get_symbol_stats(a, _ex0(), sdv);
1757 for (sym_desc_vec::iterator it=sdv.begin(); it!=sdv.end(); ++it)
1758 args.append(*it->sym);
1762 // Find the symbol to factor in at this stage
1763 if (!is_ex_of_type(args.op(0), symbol))
1764 throw (std::runtime_error("sqrfree(): invalid factorization variable"));
1765 const symbol x = ex_to<symbol>(args.op(0));
1766 // convert the argument from something in Q[X] to something in Z[X]
1767 numeric lcm = lcm_of_coefficients_denominators(a);
1768 ex tmp = multiply_lcm(a,lcm);
1770 exvector factors = sqrfree_yun(tmp,x);
1771 // construct the next list of symbols with the first element popped
1773 for (int i=1; i<args.nops(); ++i)
1774 newargs.append(args.op(i));
1775 // recurse down the factors in remaining vars
1776 if (newargs.nops()>0) {
1777 for (exvector::iterator i=factors.begin(); i!=factors.end(); ++i)
1778 *i = sqrfree(*i, newargs);
1780 // Done with recursion, now construct the final result
1782 exvector::iterator it = factors.begin();
1783 for (int p = 1; it!=factors.end(); ++it, ++p)
1784 result *= power(*it, p);
1785 // Yun's algorithm does not account for constant factors. (For
1786 // univariate polynomials it works only in the monic case.) We can
1787 // correct this by inserting what has been lost back into the result:
1788 result = result * quo(tmp, result, x);
1789 return result * lcm.inverse();
1792 /** Compute square-free partial fraction decomposition of rational function
1795 * @param a rational function over Z[x], treated as univariate polynomial
1797 * @param x variable to factor in
1798 * @return decomposed rational function */
1799 ex sqrfree_parfrac(const ex & a, const symbol & x)
1801 // Find numerator and denominator
1802 ex nd = numer_denom(a);
1803 ex numer = nd.op(0), denom = nd.op(1);
1804 //clog << "numer = " << numer << ", denom = " << denom << endl;
1806 // Convert N(x)/D(x) -> Q(x) + R(x)/D(x), so degree(R) < degree(D)
1807 ex red_poly = quo(numer, denom, x), red_numer = rem(numer, denom, x).expand();
1808 //clog << "red_poly = " << red_poly << ", red_numer = " << red_numer << endl;
1810 // Factorize denominator and compute cofactors
1811 exvector yun = sqrfree_yun(denom, x);
1812 //clog << "yun factors: " << exprseq(yun) << endl;
1813 int num_yun = yun.size();
1814 exvector factor; factor.reserve(num_yun);
1815 exvector cofac; cofac.reserve(num_yun);
1816 for (unsigned i=0; i<num_yun; i++) {
1817 if (!yun[i].is_equal(_ex1())) {
1818 for (unsigned j=0; j<=i; j++) {
1819 factor.push_back(pow(yun[i], j+1));
1821 for (unsigned k=0; k<num_yun; k++) {
1823 prod *= pow(yun[k], i-j);
1825 prod *= pow(yun[k], k+1);
1827 cofac.push_back(prod.expand());
1831 int num_factors = factor.size();
1832 //clog << "factors : " << exprseq(factor) << endl;
1833 //clog << "cofactors: " << exprseq(cofac) << endl;
1835 // Construct coefficient matrix for decomposition
1836 int max_denom_deg = denom.degree(x);
1837 matrix sys(max_denom_deg + 1, num_factors);
1838 matrix rhs(max_denom_deg + 1, 1);
1839 for (unsigned i=0; i<=max_denom_deg; i++) {
1840 for (unsigned j=0; j<num_factors; j++)
1841 sys(i, j) = cofac[j].coeff(x, i);
1842 rhs(i, 0) = red_numer.coeff(x, i);
1844 //clog << "coeffs: " << sys << endl;
1845 //clog << "rhs : " << rhs << endl;
1847 // Solve resulting linear system
1848 matrix vars(num_factors, 1);
1849 for (unsigned i=0; i<num_factors; i++)
1850 vars(i, 0) = symbol();
1851 matrix sol = sys.solve(vars, rhs);
1853 // Sum up decomposed fractions
1855 for (unsigned i=0; i<num_factors; i++)
1856 sum += sol(i, 0) / factor[i];
1858 return red_poly + sum;
1863 * Normal form of rational functions
1867 * Note: The internal normal() functions (= basic::normal() and overloaded
1868 * functions) all return lists of the form {numerator, denominator}. This
1869 * is to get around mul::eval()'s automatic expansion of numeric coefficients.
1870 * E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
1871 * the information that (a+b) is the numerator and 3 is the denominator.
1875 /** Create a symbol for replacing the expression "e" (or return a previously
1876 * assigned symbol). The symbol is appended to sym_lst and returned, the
1877 * expression is appended to repl_lst.
1878 * @see ex::normal */
1879 static ex replace_with_symbol(const ex &e, lst &sym_lst, lst &repl_lst)
1881 // Expression already in repl_lst? Then return the assigned symbol
1882 for (unsigned i=0; i<repl_lst.nops(); i++)
1883 if (repl_lst.op(i).is_equal(e))
1884 return sym_lst.op(i);
1886 // Otherwise create new symbol and add to list, taking care that the
1887 // replacement expression doesn't contain symbols from the sym_lst
1888 // because subs() is not recursive
1891 ex e_replaced = e.subs(sym_lst, repl_lst);
1893 repl_lst.append(e_replaced);
1897 /** Create a symbol for replacing the expression "e" (or return a previously
1898 * assigned symbol). An expression of the form "symbol == expression" is added
1899 * to repl_lst and the symbol is returned.
1900 * @see ex::to_rational */
1901 static ex replace_with_symbol(const ex &e, lst &repl_lst)
1903 // Expression already in repl_lst? Then return the assigned symbol
1904 for (unsigned i=0; i<repl_lst.nops(); i++)
1905 if (repl_lst.op(i).op(1).is_equal(e))
1906 return repl_lst.op(i).op(0);
1908 // Otherwise create new symbol and add to list, taking care that the
1909 // replacement expression doesn't contain symbols from the sym_lst
1910 // because subs() is not recursive
1913 ex e_replaced = e.subs(repl_lst);
1914 repl_lst.append(es == e_replaced);
1919 /** Function object to be applied by basic::normal(). */
1920 struct normal_map_function : public map_function {
1922 normal_map_function(int l) : level(l) {}
1923 ex operator()(const ex & e) { return normal(e, level); }
1926 /** Default implementation of ex::normal(). It normalizes the children and
1927 * replaces the object with a temporary symbol.
1928 * @see ex::normal */
1929 ex basic::normal(lst &sym_lst, lst &repl_lst, int level) const
1932 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1935 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1936 else if (level == -max_recursion_level)
1937 throw(std::runtime_error("max recursion level reached"));
1939 normal_map_function map_normal(level - 1);
1940 return (new lst(replace_with_symbol(map(map_normal), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1946 /** Implementation of ex::normal() for symbols. This returns the unmodified symbol.
1947 * @see ex::normal */
1948 ex symbol::normal(lst &sym_lst, lst &repl_lst, int level) const
1950 return (new lst(*this, _ex1()))->setflag(status_flags::dynallocated);
1954 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1955 * into re+I*im and replaces I and non-rational real numbers with a temporary
1957 * @see ex::normal */
1958 ex numeric::normal(lst &sym_lst, lst &repl_lst, int level) const
1960 numeric num = numer();
1963 if (num.is_real()) {
1964 if (!num.is_integer())
1965 numex = replace_with_symbol(numex, sym_lst, repl_lst);
1967 numeric re = num.real(), im = num.imag();
1968 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, sym_lst, repl_lst);
1969 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, sym_lst, repl_lst);
1970 numex = re_ex + im_ex * replace_with_symbol(I, sym_lst, repl_lst);
1973 // Denominator is always a real integer (see numeric::denom())
1974 return (new lst(numex, denom()))->setflag(status_flags::dynallocated);
1978 /** Fraction cancellation.
1979 * @param n numerator
1980 * @param d denominator
1981 * @return cancelled fraction {n, d} as a list */
1982 static ex frac_cancel(const ex &n, const ex &d)
1986 numeric pre_factor = _num1();
1988 //std::clog << "frac_cancel num = " << num << ", den = " << den << std::endl;
1990 // Handle trivial case where denominator is 1
1991 if (den.is_equal(_ex1()))
1992 return (new lst(num, den))->setflag(status_flags::dynallocated);
1994 // Handle special cases where numerator or denominator is 0
1996 return (new lst(num, _ex1()))->setflag(status_flags::dynallocated);
1997 if (den.expand().is_zero())
1998 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
2000 // Bring numerator and denominator to Z[X] by multiplying with
2001 // LCM of all coefficients' denominators
2002 numeric num_lcm = lcm_of_coefficients_denominators(num);
2003 numeric den_lcm = lcm_of_coefficients_denominators(den);
2004 num = multiply_lcm(num, num_lcm);
2005 den = multiply_lcm(den, den_lcm);
2006 pre_factor = den_lcm / num_lcm;
2008 // Cancel GCD from numerator and denominator
2010 if (gcd(num, den, &cnum, &cden, false) != _ex1()) {
2015 // Make denominator unit normal (i.e. coefficient of first symbol
2016 // as defined by get_first_symbol() is made positive)
2018 if (get_first_symbol(den, x)) {
2019 GINAC_ASSERT(is_ex_exactly_of_type(den.unit(*x),numeric));
2020 if (ex_to<numeric>(den.unit(*x)).is_negative()) {
2026 // Return result as list
2027 //std::clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << std::endl;
2028 return (new lst(num * pre_factor.numer(), den * pre_factor.denom()))->setflag(status_flags::dynallocated);
2032 /** Implementation of ex::normal() for a sum. It expands terms and performs
2033 * fractional addition.
2034 * @see ex::normal */
2035 ex add::normal(lst &sym_lst, lst &repl_lst, int level) const
2038 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
2039 else if (level == -max_recursion_level)
2040 throw(std::runtime_error("max recursion level reached"));
2042 // Normalize children and split each one into numerator and denominator
2043 exvector nums, dens;
2044 nums.reserve(seq.size()+1);
2045 dens.reserve(seq.size()+1);
2046 epvector::const_iterator it = seq.begin(), itend = seq.end();
2047 while (it != itend) {
2048 ex n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1);
2049 nums.push_back(n.op(0));
2050 dens.push_back(n.op(1));
2053 ex n = overall_coeff.bp->normal(sym_lst, repl_lst, level-1);
2054 nums.push_back(n.op(0));
2055 dens.push_back(n.op(1));
2056 GINAC_ASSERT(nums.size() == dens.size());
2058 // Now, nums is a vector of all numerators and dens is a vector of
2060 //std::clog << "add::normal uses " << nums.size() << " summands:\n";
2062 // Add fractions sequentially
2063 exvector::const_iterator num_it = nums.begin(), num_itend = nums.end();
2064 exvector::const_iterator den_it = dens.begin(), den_itend = dens.end();
2065 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
2066 ex num = *num_it++, den = *den_it++;
2067 while (num_it != num_itend) {
2068 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
2069 ex next_num = *num_it++, next_den = *den_it++;
2071 // Trivially add sequences of fractions with identical denominators
2072 while ((den_it != den_itend) && next_den.is_equal(*den_it)) {
2073 next_num += *num_it;
2077 // Additiion of two fractions, taking advantage of the fact that
2078 // the heuristic GCD algorithm computes the cofactors at no extra cost
2079 ex co_den1, co_den2;
2080 ex g = gcd(den, next_den, &co_den1, &co_den2, false);
2081 num = ((num * co_den2) + (next_num * co_den1)).expand();
2082 den *= co_den2; // this is the lcm(den, next_den)
2084 //std::clog << " common denominator = " << den << std::endl;
2086 // Cancel common factors from num/den
2087 return frac_cancel(num, den);
2091 /** Implementation of ex::normal() for a product. It cancels common factors
2093 * @see ex::normal() */
2094 ex mul::normal(lst &sym_lst, lst &repl_lst, int level) const
2097 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
2098 else if (level == -max_recursion_level)
2099 throw(std::runtime_error("max recursion level reached"));
2101 // Normalize children, separate into numerator and denominator
2105 epvector::const_iterator it = seq.begin(), itend = seq.end();
2106 while (it != itend) {
2107 n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1);
2112 n = overall_coeff.bp->normal(sym_lst, repl_lst, level-1);
2116 // Perform fraction cancellation
2117 return frac_cancel(num, den);
2121 /** Implementation of ex::normal() for powers. It normalizes the basis,
2122 * distributes integer exponents to numerator and denominator, and replaces
2123 * non-integer powers by temporary symbols.
2124 * @see ex::normal */
2125 ex power::normal(lst &sym_lst, lst &repl_lst, int level) const
2128 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
2129 else if (level == -max_recursion_level)
2130 throw(std::runtime_error("max recursion level reached"));
2132 // Normalize basis and exponent (exponent gets reassembled)
2133 ex n_basis = basis.bp->normal(sym_lst, repl_lst, level-1);
2134 ex n_exponent = exponent.bp->normal(sym_lst, repl_lst, level-1);
2135 n_exponent = n_exponent.op(0) / n_exponent.op(1);
2137 if (n_exponent.info(info_flags::integer)) {
2139 if (n_exponent.info(info_flags::positive)) {
2141 // (a/b)^n -> {a^n, b^n}
2142 return (new lst(power(n_basis.op(0), n_exponent), power(n_basis.op(1), n_exponent)))->setflag(status_flags::dynallocated);
2144 } else if (n_exponent.info(info_flags::negative)) {
2146 // (a/b)^-n -> {b^n, a^n}
2147 return (new lst(power(n_basis.op(1), -n_exponent), power(n_basis.op(0), -n_exponent)))->setflag(status_flags::dynallocated);
2152 if (n_exponent.info(info_flags::positive)) {
2154 // (a/b)^x -> {sym((a/b)^x), 1}
2155 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);
2157 } else if (n_exponent.info(info_flags::negative)) {
2159 if (n_basis.op(1).is_equal(_ex1())) {
2161 // a^-x -> {1, sym(a^x)}
2162 return (new lst(_ex1(), replace_with_symbol(power(n_basis.op(0), -n_exponent), sym_lst, repl_lst)))->setflag(status_flags::dynallocated);
2166 // (a/b)^-x -> {sym((b/a)^x), 1}
2167 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);
2170 } else { // n_exponent not numeric
2172 // (a/b)^x -> {sym((a/b)^x, 1}
2173 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 /** Implementation of ex::normal() for pseries. It normalizes each coefficient
2180 * and replaces the series by a temporary symbol.
2181 * @see ex::normal */
2182 ex pseries::normal(lst &sym_lst, lst &repl_lst, int level) const
2185 for (epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i) {
2186 ex restexp = i->rest.normal();
2187 if (!restexp.is_zero())
2188 newseq.push_back(expair(restexp, i->coeff));
2190 ex n = pseries(relational(var,point), newseq);
2191 return (new lst(replace_with_symbol(n, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
2195 /** Normalization of rational functions.
2196 * This function converts an expression to its normal form
2197 * "numerator/denominator", where numerator and denominator are (relatively
2198 * prime) polynomials. Any subexpressions which are not rational functions
2199 * (like non-rational numbers, non-integer powers or functions like sin(),
2200 * cos() etc.) are replaced by temporary symbols which are re-substituted by
2201 * the (normalized) subexpressions before normal() returns (this way, any
2202 * expression can be treated as a rational function). normal() is applied
2203 * recursively to arguments of functions etc.
2205 * @param level maximum depth of recursion
2206 * @return normalized expression */
2207 ex ex::normal(int level) const
2209 lst sym_lst, repl_lst;
2211 ex e = bp->normal(sym_lst, repl_lst, level);
2212 GINAC_ASSERT(is_ex_of_type(e, lst));
2214 // Re-insert replaced symbols
2215 if (sym_lst.nops() > 0)
2216 e = e.subs(sym_lst, repl_lst);
2218 // Convert {numerator, denominator} form back to fraction
2219 return e.op(0) / e.op(1);
2222 /** Get numerator of an expression. If the expression is not of the normal
2223 * form "numerator/denominator", it is first converted to this form and
2224 * then the numerator is returned.
2227 * @return numerator */
2228 ex ex::numer(void) const
2230 lst sym_lst, repl_lst;
2232 ex e = bp->normal(sym_lst, repl_lst, 0);
2233 GINAC_ASSERT(is_ex_of_type(e, lst));
2235 // Re-insert replaced symbols
2236 if (sym_lst.nops() > 0)
2237 return e.op(0).subs(sym_lst, repl_lst);
2242 /** Get denominator of an expression. If the expression is not of the normal
2243 * form "numerator/denominator", it is first converted to this form and
2244 * then the denominator is returned.
2247 * @return denominator */
2248 ex ex::denom(void) const
2250 lst sym_lst, repl_lst;
2252 ex e = bp->normal(sym_lst, repl_lst, 0);
2253 GINAC_ASSERT(is_ex_of_type(e, lst));
2255 // Re-insert replaced symbols
2256 if (sym_lst.nops() > 0)
2257 return e.op(1).subs(sym_lst, repl_lst);
2262 /** Get numerator and denominator of an expression. If the expresison is not
2263 * of the normal form "numerator/denominator", it is first converted to this
2264 * form and then a list [numerator, denominator] is returned.
2267 * @return a list [numerator, denominator] */
2268 ex ex::numer_denom(void) const
2270 lst sym_lst, repl_lst;
2272 ex e = bp->normal(sym_lst, repl_lst, 0);
2273 GINAC_ASSERT(is_ex_of_type(e, lst));
2275 // Re-insert replaced symbols
2276 if (sym_lst.nops() > 0)
2277 return e.subs(sym_lst, repl_lst);
2283 /** Default implementation of ex::to_rational(). It replaces the object with a
2285 * @see ex::to_rational */
2286 ex basic::to_rational(lst &repl_lst) const
2288 return replace_with_symbol(*this, repl_lst);
2292 /** Implementation of ex::to_rational() for symbols. This returns the
2293 * unmodified symbol.
2294 * @see ex::to_rational */
2295 ex symbol::to_rational(lst &repl_lst) const
2301 /** Implementation of ex::to_rational() for a numeric. It splits complex
2302 * numbers into re+I*im and replaces I and non-rational real numbers with a
2304 * @see ex::to_rational */
2305 ex numeric::to_rational(lst &repl_lst) const
2309 return replace_with_symbol(*this, repl_lst);
2311 numeric re = real();
2312 numeric im = imag();
2313 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl_lst);
2314 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl_lst);
2315 return re_ex + im_ex * replace_with_symbol(I, repl_lst);
2321 /** Implementation of ex::to_rational() for powers. It replaces non-integer
2322 * powers by temporary symbols.
2323 * @see ex::to_rational */
2324 ex power::to_rational(lst &repl_lst) const
2326 if (exponent.info(info_flags::integer))
2327 return power(basis.to_rational(repl_lst), exponent);
2329 return replace_with_symbol(*this, repl_lst);
2333 /** Implementation of ex::to_rational() for expairseqs.
2334 * @see ex::to_rational */
2335 ex expairseq::to_rational(lst &repl_lst) const
2338 s.reserve(seq.size());
2339 for (epvector::const_iterator it=seq.begin(); it!=seq.end(); ++it) {
2340 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*it).to_rational(repl_lst)));
2341 // s.push_back(combine_ex_with_coeff_to_pair((*it).rest.to_rational(repl_lst),
2343 ex oc = overall_coeff.to_rational(repl_lst);
2344 if (oc.info(info_flags::numeric))
2345 return thisexpairseq(s, overall_coeff);
2346 else s.push_back(combine_ex_with_coeff_to_pair(oc,_ex1()));
2347 return thisexpairseq(s, default_overall_coeff());
2351 /** Rationalization of non-rational functions.
2352 * This function converts a general expression to a rational polynomial
2353 * by replacing all non-rational subexpressions (like non-rational numbers,
2354 * non-integer powers or functions like sin(), cos() etc.) to temporary
2355 * symbols. This makes it possible to use functions like gcd() and divide()
2356 * on non-rational functions by applying to_rational() on the arguments,
2357 * calling the desired function and re-substituting the temporary symbols
2358 * in the result. To make the last step possible, all temporary symbols and
2359 * their associated expressions are collected in the list specified by the
2360 * repl_lst parameter in the form {symbol == expression}, ready to be passed
2361 * as an argument to ex::subs().
2363 * @param repl_lst collects a list of all temporary symbols and their replacements
2364 * @return rationalized expression */
2365 ex ex::to_rational(lst &repl_lst) const
2367 return bp->to_rational(repl_lst);
2371 } // namespace GiNaC