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-2008 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
34 #include "expairseq.h"
41 #include "relational.h"
42 #include "operators.h"
50 // If comparing expressions (ex::compare()) is fast, you can set this to 1.
51 // Some routines like quo(), rem() and gcd() will then return a quick answer
52 // when they are called with two identical arguments.
53 #define FAST_COMPARE 1
55 // Set this if you want divide_in_z() to use remembering
56 #define USE_REMEMBER 0
58 // Set this if you want divide_in_z() to use trial division followed by
59 // polynomial interpolation (always slower except for completely dense
61 #define USE_TRIAL_DIVISION 0
63 // Set this to enable some statistical output for the GCD routines
68 // Statistics variables
69 static int gcd_called = 0;
70 static int sr_gcd_called = 0;
71 static int heur_gcd_called = 0;
72 static int heur_gcd_failed = 0;
74 // Print statistics at end of program
75 static struct _stat_print {
78 std::cout << "gcd() called " << gcd_called << " times\n";
79 std::cout << "sr_gcd() called " << sr_gcd_called << " times\n";
80 std::cout << "heur_gcd() called " << heur_gcd_called << " times\n";
81 std::cout << "heur_gcd() failed " << heur_gcd_failed << " times\n";
87 /** Return pointer to first symbol found in expression. Due to GiNaC's
88 * internal ordering of terms, it may not be obvious which symbol this
89 * function returns for a given expression.
91 * @param e expression to search
92 * @param x first symbol found (returned)
93 * @return "false" if no symbol was found, "true" otherwise */
94 static bool get_first_symbol(const ex &e, ex &x)
96 if (is_a<symbol>(e)) {
99 } else if (is_exactly_a<add>(e) || is_exactly_a<mul>(e)) {
100 for (size_t i=0; i<e.nops(); i++)
101 if (get_first_symbol(e.op(i), x))
103 } else if (is_exactly_a<power>(e)) {
104 if (get_first_symbol(e.op(0), x))
112 * Statistical information about symbols in polynomials
115 /** This structure holds information about the highest and lowest degrees
116 * in which a symbol appears in two multivariate polynomials "a" and "b".
117 * A vector of these structures with information about all symbols in
118 * two polynomials can be created with the function get_symbol_stats().
120 * @see get_symbol_stats */
122 /** Reference to symbol */
125 /** Highest degree of symbol in polynomial "a" */
128 /** Highest degree of symbol in polynomial "b" */
131 /** Lowest degree of symbol in polynomial "a" */
134 /** Lowest degree of symbol in polynomial "b" */
137 /** Maximum of deg_a and deg_b (Used for sorting) */
140 /** Maximum number of terms of leading coefficient of symbol in both polynomials */
143 /** Commparison operator for sorting */
144 bool operator<(const sym_desc &x) const
146 if (max_deg == x.max_deg)
147 return max_lcnops < x.max_lcnops;
149 return max_deg < x.max_deg;
153 // Vector of sym_desc structures
154 typedef std::vector<sym_desc> sym_desc_vec;
156 // Add symbol the sym_desc_vec (used internally by get_symbol_stats())
157 static void add_symbol(const ex &s, sym_desc_vec &v)
159 sym_desc_vec::const_iterator it = v.begin(), itend = v.end();
160 while (it != itend) {
161 if (it->sym.is_equal(s)) // If it's already in there, don't add it a second time
170 // Collect all symbols of an expression (used internally by get_symbol_stats())
171 static void collect_symbols(const ex &e, sym_desc_vec &v)
173 if (is_a<symbol>(e)) {
175 } else if (is_exactly_a<add>(e) || is_exactly_a<mul>(e)) {
176 for (size_t i=0; i<e.nops(); i++)
177 collect_symbols(e.op(i), v);
178 } else if (is_exactly_a<power>(e)) {
179 collect_symbols(e.op(0), v);
183 /** Collect statistical information about symbols in polynomials.
184 * This function fills in a vector of "sym_desc" structs which contain
185 * information about the highest and lowest degrees of all symbols that
186 * appear in two polynomials. The vector is then sorted by minimum
187 * degree (lowest to highest). The information gathered by this
188 * function is used by the GCD routines to identify trivial factors
189 * and to determine which variable to choose as the main variable
190 * for GCD computation.
192 * @param a first multivariate polynomial
193 * @param b second multivariate polynomial
194 * @param v vector of sym_desc structs (filled in) */
195 static void get_symbol_stats(const ex &a, const ex &b, sym_desc_vec &v)
197 collect_symbols(a.eval(), v); // eval() to expand assigned symbols
198 collect_symbols(b.eval(), v);
199 sym_desc_vec::iterator it = v.begin(), itend = v.end();
200 while (it != itend) {
201 int deg_a = a.degree(it->sym);
202 int deg_b = b.degree(it->sym);
205 it->max_deg = std::max(deg_a, deg_b);
206 it->max_lcnops = std::max(a.lcoeff(it->sym).nops(), b.lcoeff(it->sym).nops());
207 it->ldeg_a = a.ldegree(it->sym);
208 it->ldeg_b = b.ldegree(it->sym);
211 std::sort(v.begin(), v.end());
214 std::clog << "Symbols:\n";
215 it = v.begin(); itend = v.end();
216 while (it != itend) {
217 std::clog << " " << it->sym << ": deg_a=" << it->deg_a << ", deg_b=" << it->deg_b << ", ldeg_a=" << it->ldeg_a << ", ldeg_b=" << it->ldeg_b << ", max_deg=" << it->max_deg << ", max_lcnops=" << it->max_lcnops << endl;
218 std::clog << " lcoeff_a=" << a.lcoeff(it->sym) << ", lcoeff_b=" << b.lcoeff(it->sym) << endl;
226 * Computation of LCM of denominators of coefficients of a polynomial
229 // Compute LCM of denominators of coefficients by going through the
230 // expression recursively (used internally by lcm_of_coefficients_denominators())
231 static numeric lcmcoeff(const ex &e, const numeric &l)
233 if (e.info(info_flags::rational))
234 return lcm(ex_to<numeric>(e).denom(), l);
235 else if (is_exactly_a<add>(e)) {
236 numeric c = *_num1_p;
237 for (size_t i=0; i<e.nops(); i++)
238 c = lcmcoeff(e.op(i), c);
240 } else if (is_exactly_a<mul>(e)) {
241 numeric c = *_num1_p;
242 for (size_t i=0; i<e.nops(); i++)
243 c *= lcmcoeff(e.op(i), *_num1_p);
245 } else if (is_exactly_a<power>(e)) {
246 if (is_a<symbol>(e.op(0)))
249 return pow(lcmcoeff(e.op(0), l), ex_to<numeric>(e.op(1)));
254 /** Compute LCM of denominators of coefficients of a polynomial.
255 * Given a polynomial with rational coefficients, this function computes
256 * the LCM of the denominators of all coefficients. This can be used
257 * to bring a polynomial from Q[X] to Z[X].
259 * @param e multivariate polynomial (need not be expanded)
260 * @return LCM of denominators of coefficients */
261 static numeric lcm_of_coefficients_denominators(const ex &e)
263 return lcmcoeff(e, *_num1_p);
266 /** Bring polynomial from Q[X] to Z[X] by multiplying in the previously
267 * determined LCM of the coefficient's denominators.
269 * @param e multivariate polynomial (need not be expanded)
270 * @param lcm LCM to multiply in */
271 static ex multiply_lcm(const ex &e, const numeric &lcm)
273 if (is_exactly_a<mul>(e)) {
274 size_t num = e.nops();
275 exvector v; v.reserve(num + 1);
276 numeric lcm_accum = *_num1_p;
277 for (size_t i=0; i<num; i++) {
278 numeric op_lcm = lcmcoeff(e.op(i), *_num1_p);
279 v.push_back(multiply_lcm(e.op(i), op_lcm));
282 v.push_back(lcm / lcm_accum);
283 return (new mul(v))->setflag(status_flags::dynallocated);
284 } else if (is_exactly_a<add>(e)) {
285 size_t num = e.nops();
286 exvector v; v.reserve(num);
287 for (size_t i=0; i<num; i++)
288 v.push_back(multiply_lcm(e.op(i), lcm));
289 return (new add(v))->setflag(status_flags::dynallocated);
290 } else if (is_exactly_a<power>(e)) {
291 if (is_a<symbol>(e.op(0)))
294 return pow(multiply_lcm(e.op(0), lcm.power(ex_to<numeric>(e.op(1)).inverse())), e.op(1));
300 /** Compute the integer content (= GCD of all numeric coefficients) of an
301 * expanded polynomial. For a polynomial with rational coefficients, this
302 * returns g/l where g is the GCD of the coefficients' numerators and l
303 * is the LCM of the coefficients' denominators.
305 * @return integer content */
306 numeric ex::integer_content() const
308 return bp->integer_content();
311 numeric basic::integer_content() const
316 numeric numeric::integer_content() const
321 numeric add::integer_content() const
323 epvector::const_iterator it = seq.begin();
324 epvector::const_iterator itend = seq.end();
325 numeric c = *_num0_p, l = *_num1_p;
326 while (it != itend) {
327 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
328 GINAC_ASSERT(is_exactly_a<numeric>(it->coeff));
329 c = gcd(ex_to<numeric>(it->coeff).numer(), c);
330 l = lcm(ex_to<numeric>(it->coeff).denom(), l);
333 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
334 c = gcd(ex_to<numeric>(overall_coeff).numer(), c);
335 l = lcm(ex_to<numeric>(overall_coeff).denom(), l);
339 numeric mul::integer_content() const
341 #ifdef DO_GINAC_ASSERT
342 epvector::const_iterator it = seq.begin();
343 epvector::const_iterator itend = seq.end();
344 while (it != itend) {
345 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
348 #endif // def DO_GINAC_ASSERT
349 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
350 return abs(ex_to<numeric>(overall_coeff));
355 * Polynomial quotients and remainders
358 /** Quotient q(x) of polynomials a(x) and b(x) in Q[x].
359 * It satisfies a(x)=b(x)*q(x)+r(x).
361 * @param a first polynomial in x (dividend)
362 * @param b second polynomial in x (divisor)
363 * @param x a and b are polynomials in x
364 * @param check_args check whether a and b are polynomials with rational
365 * coefficients (defaults to "true")
366 * @return quotient of a and b in Q[x] */
367 ex quo(const ex &a, const ex &b, const ex &x, bool check_args)
370 throw(std::overflow_error("quo: division by zero"));
371 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b))
377 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
378 throw(std::invalid_argument("quo: arguments must be polynomials over the rationals"));
380 // Polynomial long division
384 int bdeg = b.degree(x);
385 int rdeg = r.degree(x);
386 ex blcoeff = b.expand().coeff(x, bdeg);
387 bool blcoeff_is_numeric = is_exactly_a<numeric>(blcoeff);
388 exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
389 while (rdeg >= bdeg) {
390 ex term, rcoeff = r.coeff(x, rdeg);
391 if (blcoeff_is_numeric)
392 term = rcoeff / blcoeff;
394 if (!divide(rcoeff, blcoeff, term, false))
395 return (new fail())->setflag(status_flags::dynallocated);
397 term *= power(x, rdeg - bdeg);
399 r -= (term * b).expand();
404 return (new add(v))->setflag(status_flags::dynallocated);
408 /** Remainder r(x) of polynomials a(x) and b(x) in Q[x].
409 * It satisfies a(x)=b(x)*q(x)+r(x).
411 * @param a first polynomial in x (dividend)
412 * @param b second polynomial in x (divisor)
413 * @param x a and b are polynomials in x
414 * @param check_args check whether a and b are polynomials with rational
415 * coefficients (defaults to "true")
416 * @return remainder of a(x) and b(x) in Q[x] */
417 ex rem(const ex &a, const ex &b, const ex &x, bool check_args)
420 throw(std::overflow_error("rem: division by zero"));
421 if (is_exactly_a<numeric>(a)) {
422 if (is_exactly_a<numeric>(b))
431 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
432 throw(std::invalid_argument("rem: arguments must be polynomials over the rationals"));
434 // Polynomial long division
438 int bdeg = b.degree(x);
439 int rdeg = r.degree(x);
440 ex blcoeff = b.expand().coeff(x, bdeg);
441 bool blcoeff_is_numeric = is_exactly_a<numeric>(blcoeff);
442 while (rdeg >= bdeg) {
443 ex term, rcoeff = r.coeff(x, rdeg);
444 if (blcoeff_is_numeric)
445 term = rcoeff / blcoeff;
447 if (!divide(rcoeff, blcoeff, term, false))
448 return (new fail())->setflag(status_flags::dynallocated);
450 term *= power(x, rdeg - bdeg);
451 r -= (term * b).expand();
460 /** Decompose rational function a(x)=N(x)/D(x) into P(x)+n(x)/D(x)
461 * with degree(n, x) < degree(D, x).
463 * @param a rational function in x
464 * @param x a is a function of x
465 * @return decomposed function. */
466 ex decomp_rational(const ex &a, const ex &x)
468 ex nd = numer_denom(a);
469 ex numer = nd.op(0), denom = nd.op(1);
470 ex q = quo(numer, denom, x);
471 if (is_exactly_a<fail>(q))
474 return q + rem(numer, denom, x) / denom;
478 /** Pseudo-remainder of polynomials a(x) and b(x) in Q[x].
480 * @param a first polynomial in x (dividend)
481 * @param b second polynomial in x (divisor)
482 * @param x a and b are polynomials in x
483 * @param check_args check whether a and b are polynomials with rational
484 * coefficients (defaults to "true")
485 * @return pseudo-remainder of a(x) and b(x) in Q[x] */
486 ex prem(const ex &a, const ex &b, const ex &x, bool check_args)
489 throw(std::overflow_error("prem: division by zero"));
490 if (is_exactly_a<numeric>(a)) {
491 if (is_exactly_a<numeric>(b))
496 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
497 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
499 // Polynomial long division
502 int rdeg = r.degree(x);
503 int bdeg = eb.degree(x);
506 blcoeff = eb.coeff(x, bdeg);
510 eb -= blcoeff * power(x, bdeg);
514 int delta = rdeg - bdeg + 1, i = 0;
515 while (rdeg >= bdeg && !r.is_zero()) {
516 ex rlcoeff = r.coeff(x, rdeg);
517 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
521 r -= rlcoeff * power(x, rdeg);
522 r = (blcoeff * r).expand() - term;
526 return power(blcoeff, delta - i) * r;
530 /** Sparse pseudo-remainder of polynomials a(x) and b(x) in Q[x].
532 * @param a first polynomial in x (dividend)
533 * @param b second polynomial in x (divisor)
534 * @param x a and b are polynomials in x
535 * @param check_args check whether a and b are polynomials with rational
536 * coefficients (defaults to "true")
537 * @return sparse pseudo-remainder of a(x) and b(x) in Q[x] */
538 ex sprem(const ex &a, const ex &b, const ex &x, bool check_args)
541 throw(std::overflow_error("prem: division by zero"));
542 if (is_exactly_a<numeric>(a)) {
543 if (is_exactly_a<numeric>(b))
548 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
549 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
551 // Polynomial long division
554 int rdeg = r.degree(x);
555 int bdeg = eb.degree(x);
558 blcoeff = eb.coeff(x, bdeg);
562 eb -= blcoeff * power(x, bdeg);
566 while (rdeg >= bdeg && !r.is_zero()) {
567 ex rlcoeff = r.coeff(x, rdeg);
568 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
572 r -= rlcoeff * power(x, rdeg);
573 r = (blcoeff * r).expand() - term;
580 /** Exact polynomial division of a(X) by b(X) in Q[X].
582 * @param a first multivariate polynomial (dividend)
583 * @param b second multivariate polynomial (divisor)
584 * @param q quotient (returned)
585 * @param check_args check whether a and b are polynomials with rational
586 * coefficients (defaults to "true")
587 * @return "true" when exact division succeeds (quotient returned in q),
588 * "false" otherwise (q left untouched) */
589 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
592 throw(std::overflow_error("divide: division by zero"));
597 if (is_exactly_a<numeric>(b)) {
600 } else if (is_exactly_a<numeric>(a))
608 if (check_args && (!a.info(info_flags::rational_polynomial) ||
609 !b.info(info_flags::rational_polynomial)))
610 throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
614 if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
615 throw(std::invalid_argument("invalid expression in divide()"));
617 // Try to avoid expanding partially factored expressions.
618 if (is_exactly_a<mul>(b)) {
619 // Divide sequentially by each term
620 ex rem_new, rem_old = a;
621 for (size_t i=0; i < b.nops(); i++) {
622 if (! divide(rem_old, b.op(i), rem_new, false))
628 } else if (is_exactly_a<power>(b)) {
629 const ex& bb(b.op(0));
630 int exp_b = ex_to<numeric>(b.op(1)).to_int();
631 ex rem_new, rem_old = a;
632 for (int i=exp_b; i>0; i--) {
633 if (! divide(rem_old, bb, rem_new, false))
641 if (is_exactly_a<mul>(a)) {
642 // Divide sequentially each term. If some term in a is divisible
643 // by b we are done... and if not, we can't really say anything.
646 bool divisible_p = false;
647 for (i=0; i < a.nops(); ++i) {
648 if (divide(a.op(i), b, rem_i, false)) {
655 resv.reserve(a.nops());
656 for (size_t j=0; j < a.nops(); j++) {
658 resv.push_back(rem_i);
660 resv.push_back(a.op(j));
662 q = (new mul(resv))->setflag(status_flags::dynallocated);
665 } else if (is_exactly_a<power>(a)) {
666 // The base itself might be divisible by b, in that case we don't
668 const ex& ab(a.op(0));
669 int a_exp = ex_to<numeric>(a.op(1)).to_int();
671 if (divide(ab, b, rem_i, false)) {
672 q = rem_i*power(ab, a_exp - 1);
675 // code below is commented-out because it leads to a significant slowdown
676 // for (int i=2; i < a_exp; i++) {
677 // if (divide(power(ab, i), b, rem_i, false)) {
678 // q = rem_i*power(ab, a_exp - i);
681 // } // ... so we *really* need to expand expression.
684 // Polynomial long division (recursive)
690 int bdeg = b.degree(x);
691 int rdeg = r.degree(x);
692 ex blcoeff = b.expand().coeff(x, bdeg);
693 bool blcoeff_is_numeric = is_exactly_a<numeric>(blcoeff);
694 exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
695 while (rdeg >= bdeg) {
696 ex term, rcoeff = r.coeff(x, rdeg);
697 if (blcoeff_is_numeric)
698 term = rcoeff / blcoeff;
700 if (!divide(rcoeff, blcoeff, term, false))
702 term *= power(x, rdeg - bdeg);
704 r -= (term * b).expand();
706 q = (new add(v))->setflag(status_flags::dynallocated);
720 typedef std::pair<ex, ex> ex2;
721 typedef std::pair<ex, bool> exbool;
724 bool operator() (const ex2 &p, const ex2 &q) const
726 int cmp = p.first.compare(q.first);
727 return ((cmp<0) || (!(cmp>0) && p.second.compare(q.second)<0));
731 typedef std::map<ex2, exbool, ex2_less> ex2_exbool_remember;
735 /** Exact polynomial division of a(X) by b(X) in Z[X].
736 * This functions works like divide() but the input and output polynomials are
737 * in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
738 * divide(), it doesn't check whether the input polynomials really are integer
739 * polynomials, so be careful of what you pass in. Also, you have to run
740 * get_symbol_stats() over the input polynomials before calling this function
741 * and pass an iterator to the first element of the sym_desc vector. This
742 * function is used internally by the heur_gcd().
744 * @param a first multivariate polynomial (dividend)
745 * @param b second multivariate polynomial (divisor)
746 * @param q quotient (returned)
747 * @param var iterator to first element of vector of sym_desc structs
748 * @return "true" when exact division succeeds (the quotient is returned in
749 * q), "false" otherwise.
750 * @see get_symbol_stats, heur_gcd */
751 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
755 throw(std::overflow_error("divide_in_z: division by zero"));
756 if (b.is_equal(_ex1)) {
760 if (is_exactly_a<numeric>(a)) {
761 if (is_exactly_a<numeric>(b)) {
763 return q.info(info_flags::integer);
776 static ex2_exbool_remember dr_remember;
777 ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
778 if (remembered != dr_remember.end()) {
779 q = remembered->second.first;
780 return remembered->second.second;
784 if (is_exactly_a<power>(b)) {
785 const ex& bb(b.op(0));
787 int exp_b = ex_to<numeric>(b.op(1)).to_int();
788 for (int i=exp_b; i>0; i--) {
789 if (!divide_in_z(qbar, bb, q, var))
796 if (is_exactly_a<mul>(b)) {
798 for (const_iterator itrb = b.begin(); itrb != b.end(); ++itrb) {
799 sym_desc_vec sym_stats;
800 get_symbol_stats(a, *itrb, sym_stats);
801 if (!divide_in_z(qbar, *itrb, q, sym_stats.begin()))
810 const ex &x = var->sym;
813 int adeg = a.degree(x), bdeg = b.degree(x);
817 #if USE_TRIAL_DIVISION
819 // Trial division with polynomial interpolation
822 // Compute values at evaluation points 0..adeg
823 vector<numeric> alpha; alpha.reserve(adeg + 1);
824 exvector u; u.reserve(adeg + 1);
825 numeric point = *_num0_p;
827 for (i=0; i<=adeg; i++) {
828 ex bs = b.subs(x == point, subs_options::no_pattern);
829 while (bs.is_zero()) {
831 bs = b.subs(x == point, subs_options::no_pattern);
833 if (!divide_in_z(a.subs(x == point, subs_options::no_pattern), bs, c, var+1))
835 alpha.push_back(point);
841 vector<numeric> rcp; rcp.reserve(adeg + 1);
842 rcp.push_back(*_num0_p);
843 for (k=1; k<=adeg; k++) {
844 numeric product = alpha[k] - alpha[0];
846 product *= alpha[k] - alpha[i];
847 rcp.push_back(product.inverse());
850 // Compute Newton coefficients
851 exvector v; v.reserve(adeg + 1);
853 for (k=1; k<=adeg; k++) {
855 for (i=k-2; i>=0; i--)
856 temp = temp * (alpha[k] - alpha[i]) + v[i];
857 v.push_back((u[k] - temp) * rcp[k]);
860 // Convert from Newton form to standard form
862 for (k=adeg-1; k>=0; k--)
863 c = c * (x - alpha[k]) + v[k];
865 if (c.degree(x) == (adeg - bdeg)) {
873 // Polynomial long division (recursive)
879 ex blcoeff = eb.coeff(x, bdeg);
880 exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
881 while (rdeg >= bdeg) {
882 ex term, rcoeff = r.coeff(x, rdeg);
883 if (!divide_in_z(rcoeff, blcoeff, term, var+1))
885 term = (term * power(x, rdeg - bdeg)).expand();
887 r -= (term * eb).expand();
889 q = (new add(v))->setflag(status_flags::dynallocated);
891 dr_remember[ex2(a, b)] = exbool(q, true);
898 dr_remember[ex2(a, b)] = exbool(q, false);
907 * Separation of unit part, content part and primitive part of polynomials
910 /** Compute unit part (= sign of leading coefficient) of a multivariate
911 * polynomial in Q[x]. The product of unit part, content part, and primitive
912 * part is the polynomial itself.
914 * @param x main variable
916 * @see ex::content, ex::primpart, ex::unitcontprim */
917 ex ex::unit(const ex &x) const
919 ex c = expand().lcoeff(x);
920 if (is_exactly_a<numeric>(c))
921 return c.info(info_flags::negative) ?_ex_1 : _ex1;
924 if (get_first_symbol(c, y))
927 throw(std::invalid_argument("invalid expression in unit()"));
932 /** Compute content part (= unit normal GCD of all coefficients) of a
933 * multivariate polynomial in Q[x]. The product of unit part, content part,
934 * and primitive part is the polynomial itself.
936 * @param x main variable
937 * @return content part
938 * @see ex::unit, ex::primpart, ex::unitcontprim */
939 ex ex::content(const ex &x) const
941 if (is_exactly_a<numeric>(*this))
942 return info(info_flags::negative) ? -*this : *this;
948 // First, divide out the integer content (which we can calculate very efficiently).
949 // If the leading coefficient of the quotient is an integer, we are done.
950 ex c = e.integer_content();
952 int deg = r.degree(x);
953 ex lcoeff = r.coeff(x, deg);
954 if (lcoeff.info(info_flags::integer))
957 // GCD of all coefficients
958 int ldeg = r.ldegree(x);
960 return lcoeff * c / lcoeff.unit(x);
962 for (int i=ldeg; i<=deg; i++)
963 cont = gcd(r.coeff(x, i), cont, NULL, NULL, false);
968 /** Compute primitive part of a multivariate polynomial in Q[x]. The result
969 * will be a unit-normal polynomial with a content part of 1. The product
970 * of unit part, content part, and primitive part is the polynomial itself.
972 * @param x main variable
973 * @return primitive part
974 * @see ex::unit, ex::content, ex::unitcontprim */
975 ex ex::primpart(const ex &x) const
977 // We need to compute the unit and content anyway, so call unitcontprim()
979 unitcontprim(x, u, c, p);
984 /** Compute primitive part of a multivariate polynomial in Q[x] when the
985 * content part is already known. This function is faster in computing the
986 * primitive part than the previous function.
988 * @param x main variable
989 * @param c previously computed content part
990 * @return primitive part */
991 ex ex::primpart(const ex &x, const ex &c) const
993 if (is_zero() || c.is_zero())
995 if (is_exactly_a<numeric>(*this))
998 // Divide by unit and content to get primitive part
1000 if (is_exactly_a<numeric>(c))
1001 return *this / (c * u);
1003 return quo(*this, c * u, x, false);
1007 /** Compute unit part, content part, and primitive part of a multivariate
1008 * polynomial in Q[x]. The product of the three parts is the polynomial
1011 * @param x main variable
1012 * @param u unit part (returned)
1013 * @param c content part (returned)
1014 * @param p primitive part (returned)
1015 * @see ex::unit, ex::content, ex::primpart */
1016 void ex::unitcontprim(const ex &x, ex &u, ex &c, ex &p) const
1018 // Quick check for zero (avoid expanding)
1025 // Special case: input is a number
1026 if (is_exactly_a<numeric>(*this)) {
1027 if (info(info_flags::negative)) {
1029 c = abs(ex_to<numeric>(*this));
1038 // Expand input polynomial
1046 // Compute unit and content
1050 // Divide by unit and content to get primitive part
1055 if (is_exactly_a<numeric>(c))
1056 p = *this / (c * u);
1058 p = quo(e, c * u, x, false);
1063 * GCD of multivariate polynomials
1066 /** Compute GCD of multivariate polynomials using the subresultant PRS
1067 * algorithm. This function is used internally by gcd().
1069 * @param a first multivariate polynomial
1070 * @param b second multivariate polynomial
1071 * @param var iterator to first element of vector of sym_desc structs
1072 * @return the GCD as a new expression
1075 static ex sr_gcd(const ex &a, const ex &b, sym_desc_vec::const_iterator var)
1081 // The first symbol is our main variable
1082 const ex &x = var->sym;
1084 // Sort c and d so that c has higher degree
1086 int adeg = a.degree(x), bdeg = b.degree(x);
1100 // Remove content from c and d, to be attached to GCD later
1101 ex cont_c = c.content(x);
1102 ex cont_d = d.content(x);
1103 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1106 c = c.primpart(x, cont_c);
1107 d = d.primpart(x, cont_d);
1109 // First element of subresultant sequence
1110 ex r = _ex0, ri = _ex1, psi = _ex1;
1111 int delta = cdeg - ddeg;
1115 // Calculate polynomial pseudo-remainder
1116 r = prem(c, d, x, false);
1118 return gamma * d.primpart(x);
1122 if (!divide_in_z(r, ri * pow(psi, delta), d, var))
1123 throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
1126 if (is_exactly_a<numeric>(r))
1129 return gamma * r.primpart(x);
1132 // Next element of subresultant sequence
1133 ri = c.expand().lcoeff(x);
1137 divide_in_z(pow(ri, delta), pow(psi, delta-1), psi, var+1);
1138 delta = cdeg - ddeg;
1143 /** Return maximum (absolute value) coefficient of a polynomial.
1144 * This function is used internally by heur_gcd().
1146 * @return maximum coefficient
1148 numeric ex::max_coefficient() const
1150 return bp->max_coefficient();
1153 /** Implementation ex::max_coefficient().
1155 numeric basic::max_coefficient() const
1160 numeric numeric::max_coefficient() const
1165 numeric add::max_coefficient() const
1167 epvector::const_iterator it = seq.begin();
1168 epvector::const_iterator itend = seq.end();
1169 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1170 numeric cur_max = abs(ex_to<numeric>(overall_coeff));
1171 while (it != itend) {
1173 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
1174 a = abs(ex_to<numeric>(it->coeff));
1182 numeric mul::max_coefficient() const
1184 #ifdef DO_GINAC_ASSERT
1185 epvector::const_iterator it = seq.begin();
1186 epvector::const_iterator itend = seq.end();
1187 while (it != itend) {
1188 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
1191 #endif // def DO_GINAC_ASSERT
1192 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1193 return abs(ex_to<numeric>(overall_coeff));
1197 /** Apply symmetric modular homomorphism to an expanded multivariate
1198 * polynomial. This function is usually used internally by heur_gcd().
1201 * @return mapped polynomial
1203 ex basic::smod(const numeric &xi) const
1208 ex numeric::smod(const numeric &xi) const
1210 return GiNaC::smod(*this, xi);
1213 ex add::smod(const numeric &xi) const
1216 newseq.reserve(seq.size()+1);
1217 epvector::const_iterator it = seq.begin();
1218 epvector::const_iterator itend = seq.end();
1219 while (it != itend) {
1220 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
1221 numeric coeff = GiNaC::smod(ex_to<numeric>(it->coeff), xi);
1222 if (!coeff.is_zero())
1223 newseq.push_back(expair(it->rest, coeff));
1226 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1227 numeric coeff = GiNaC::smod(ex_to<numeric>(overall_coeff), xi);
1228 return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
1231 ex mul::smod(const numeric &xi) const
1233 #ifdef DO_GINAC_ASSERT
1234 epvector::const_iterator it = seq.begin();
1235 epvector::const_iterator itend = seq.end();
1236 while (it != itend) {
1237 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
1240 #endif // def DO_GINAC_ASSERT
1241 mul * mulcopyp = new mul(*this);
1242 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1243 mulcopyp->overall_coeff = GiNaC::smod(ex_to<numeric>(overall_coeff),xi);
1244 mulcopyp->clearflag(status_flags::evaluated);
1245 mulcopyp->clearflag(status_flags::hash_calculated);
1246 return mulcopyp->setflag(status_flags::dynallocated);
1250 /** xi-adic polynomial interpolation */
1251 static ex interpolate(const ex &gamma, const numeric &xi, const ex &x, int degree_hint = 1)
1253 exvector g; g.reserve(degree_hint);
1255 numeric rxi = xi.inverse();
1256 for (int i=0; !e.is_zero(); i++) {
1258 g.push_back(gi * power(x, i));
1261 return (new add(g))->setflag(status_flags::dynallocated);
1264 /** Exception thrown by heur_gcd() to signal failure. */
1265 class gcdheu_failed {};
1267 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1268 * get_symbol_stats() must have been called previously with the input
1269 * polynomials and an iterator to the first element of the sym_desc vector
1270 * passed in. This function is used internally by gcd().
1272 * @param a first integer multivariate polynomial (expanded)
1273 * @param b second integer multivariate polynomial (expanded)
1274 * @param ca cofactor of polynomial a (returned), NULL to suppress
1275 * calculation of cofactor
1276 * @param cb cofactor of polynomial b (returned), NULL to suppress
1277 * calculation of cofactor
1278 * @param var iterator to first element of vector of sym_desc structs
1279 * @param res the GCD (returned)
1280 * @return true if GCD was computed, false otherwise.
1282 * @exception gcdheu_failed() */
1283 static bool heur_gcd_z(ex& res, const ex &a, const ex &b, ex *ca, ex *cb,
1284 sym_desc_vec::const_iterator var)
1290 // Algorithm only works for non-vanishing input polynomials
1291 if (a.is_zero() || b.is_zero())
1294 // GCD of two numeric values -> CLN
1295 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b)) {
1296 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1298 *ca = ex_to<numeric>(a) / g;
1300 *cb = ex_to<numeric>(b) / g;
1305 // The first symbol is our main variable
1306 const ex &x = var->sym;
1308 // Remove integer content
1309 numeric gc = gcd(a.integer_content(), b.integer_content());
1310 numeric rgc = gc.inverse();
1313 int maxdeg = std::max(p.degree(x), q.degree(x));
1315 // Find evaluation point
1316 numeric mp = p.max_coefficient();
1317 numeric mq = q.max_coefficient();
1320 xi = mq * (*_num2_p) + (*_num2_p);
1322 xi = mp * (*_num2_p) + (*_num2_p);
1325 for (int t=0; t<6; t++) {
1326 if (xi.int_length() * maxdeg > 100000) {
1327 throw gcdheu_failed();
1330 // Apply evaluation homomorphism and calculate GCD
1333 bool found = heur_gcd_z(gamma,
1334 p.subs(x == xi, subs_options::no_pattern),
1335 q.subs(x == xi, subs_options::no_pattern),
1338 gamma = gamma.expand();
1339 // Reconstruct polynomial from GCD of mapped polynomials
1340 ex g = interpolate(gamma, xi, x, maxdeg);
1342 // Remove integer content
1343 g /= g.integer_content();
1345 // If the calculated polynomial divides both p and q, this is the GCD
1347 if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1354 // Next evaluation point
1355 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1360 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1361 * get_symbol_stats() must have been called previously with the input
1362 * polynomials and an iterator to the first element of the sym_desc vector
1363 * passed in. This function is used internally by gcd().
1365 * @param a first rational multivariate polynomial (expanded)
1366 * @param b second rational multivariate polynomial (expanded)
1367 * @param ca cofactor of polynomial a (returned), NULL to suppress
1368 * calculation of cofactor
1369 * @param cb cofactor of polynomial b (returned), NULL to suppress
1370 * calculation of cofactor
1371 * @param var iterator to first element of vector of sym_desc structs
1372 * @param res the GCD (returned)
1373 * @return true if GCD was computed, false otherwise.
1377 static bool heur_gcd(ex& res, const ex& a, const ex& b, ex *ca, ex *cb,
1378 sym_desc_vec::const_iterator var)
1380 if (a.info(info_flags::integer_polynomial) &&
1381 b.info(info_flags::integer_polynomial)) {
1383 return heur_gcd_z(res, a, b, ca, cb, var);
1384 } catch (gcdheu_failed) {
1389 // convert polynomials to Z[X]
1390 const numeric a_lcm = lcm_of_coefficients_denominators(a);
1391 const numeric ab_lcm = lcmcoeff(b, a_lcm);
1393 const ex ai = a*ab_lcm;
1394 const ex bi = b*ab_lcm;
1395 if (!ai.info(info_flags::integer_polynomial))
1396 throw std::logic_error("heur_gcd: not an integer polynomial [1]");
1398 if (!bi.info(info_flags::integer_polynomial))
1399 throw std::logic_error("heur_gcd: not an integer polynomial [2]");
1403 found = heur_gcd_z(res, ai, bi, ca, cb, var);
1404 } catch (gcdheu_failed) {
1408 // GCD is not unique, it's defined up to a unit (i.e. invertible
1409 // element). If the coefficient ring is a field, every its element is
1410 // invertible, so one can multiply the polynomial GCD with any element
1411 // of the coefficient field. We use this ambiguity to make cofactors
1412 // integer polynomials.
1419 // gcd helper to handle partially factored polynomials (to avoid expanding
1420 // large expressions). At least one of the arguments should be a power.
1421 static ex gcd_pf_pow(const ex& a, const ex& b, ex* ca, ex* cb);
1423 // gcd helper to handle partially factored polynomials (to avoid expanding
1424 // large expressions). At least one of the arguments should be a product.
1425 static ex gcd_pf_mul(const ex& a, const ex& b, ex* ca, ex* cb);
1427 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1428 * and b(X) in Z[X]. Optionally also compute the cofactors of a and b,
1429 * defined by a = ca * gcd(a, b) and b = cb * gcd(a, b).
1431 * @param a first multivariate polynomial
1432 * @param b second multivariate polynomial
1433 * @param ca pointer to expression that will receive the cofactor of a, or NULL
1434 * @param cb pointer to expression that will receive the cofactor of b, or NULL
1435 * @param check_args check whether a and b are polynomials with rational
1436 * coefficients (defaults to "true")
1437 * @return the GCD as a new expression */
1438 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args, unsigned options)
1444 // GCD of numerics -> CLN
1445 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b)) {
1446 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1455 *ca = ex_to<numeric>(a) / g;
1457 *cb = ex_to<numeric>(b) / g;
1464 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))) {
1465 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1468 // Partially factored cases (to avoid expanding large expressions)
1469 if (!(options & gcd_options::no_part_factored)) {
1470 if (is_exactly_a<mul>(a) || is_exactly_a<mul>(b))
1471 return gcd_pf_mul(a, b, ca, cb);
1473 if (is_exactly_a<power>(a) || is_exactly_a<power>(b))
1474 return gcd_pf_pow(a, b, ca, cb);
1478 // Some trivial cases
1479 ex aex = a.expand(), bex = b.expand();
1480 if (aex.is_zero()) {
1487 if (bex.is_zero()) {
1494 if (aex.is_equal(_ex1) || bex.is_equal(_ex1)) {
1502 if (a.is_equal(b)) {
1511 if (is_a<symbol>(aex)) {
1512 if (! bex.subs(aex==_ex0, subs_options::no_pattern).is_zero()) {
1521 if (is_a<symbol>(bex)) {
1522 if (! aex.subs(bex==_ex0, subs_options::no_pattern).is_zero()) {
1531 if (is_exactly_a<numeric>(aex)) {
1532 numeric bcont = bex.integer_content();
1533 numeric g = gcd(ex_to<numeric>(aex), bcont);
1535 *ca = ex_to<numeric>(aex)/g;
1541 if (is_exactly_a<numeric>(bex)) {
1542 numeric acont = aex.integer_content();
1543 numeric g = gcd(ex_to<numeric>(bex), acont);
1547 *cb = ex_to<numeric>(bex)/g;
1551 // Gather symbol statistics
1552 sym_desc_vec sym_stats;
1553 get_symbol_stats(a, b, sym_stats);
1555 // The symbol with least degree which is contained in both polynomials
1556 // is our main variable
1557 sym_desc_vec::iterator vari = sym_stats.begin();
1558 while ((vari != sym_stats.end()) &&
1559 (((vari->ldeg_b == 0) && (vari->deg_b == 0)) ||
1560 ((vari->ldeg_a == 0) && (vari->deg_a == 0))))
1563 // No common symbols at all, just return 1:
1564 if (vari == sym_stats.end()) {
1565 // N.B: keep cofactors factored
1572 // move symbols which contained only in one of the polynomials
1574 rotate(sym_stats.begin(), vari, sym_stats.end());
1576 sym_desc_vec::const_iterator var = sym_stats.begin();
1577 const ex &x = var->sym;
1579 // Cancel trivial common factor
1580 int ldeg_a = var->ldeg_a;
1581 int ldeg_b = var->ldeg_b;
1582 int min_ldeg = std::min(ldeg_a,ldeg_b);
1584 ex common = power(x, min_ldeg);
1585 return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1588 // Try to eliminate variables
1589 if (var->deg_a == 0 && var->deg_b != 0 ) {
1590 ex bex_u, bex_c, bex_p;
1591 bex.unitcontprim(x, bex_u, bex_c, bex_p);
1592 ex g = gcd(aex, bex_c, ca, cb, false);
1594 *cb *= bex_u * bex_p;
1596 } else if (var->deg_b == 0 && var->deg_a != 0) {
1597 ex aex_u, aex_c, aex_p;
1598 aex.unitcontprim(x, aex_u, aex_c, aex_p);
1599 ex g = gcd(aex_c, bex, ca, cb, false);
1601 *ca *= aex_u * aex_p;
1605 // Try heuristic algorithm first, fall back to PRS if that failed
1607 if (!(options & gcd_options::no_heur_gcd)) {
1608 bool found = heur_gcd(g, aex, bex, ca, cb, var);
1610 // heur_gcd have already computed cofactors...
1611 if (g.is_equal(_ex1)) {
1612 // ... but we want to keep them factored if possible.
1627 g = sr_gcd(aex, bex, var);
1628 if (g.is_equal(_ex1)) {
1629 // Keep cofactors factored if possible
1636 divide(aex, g, *ca, false);
1638 divide(bex, g, *cb, false);
1643 // gcd helper to handle partially factored polynomials (to avoid expanding
1644 // large expressions). Both arguments should be powers.
1645 static ex gcd_pf_pow_pow(const ex& a, const ex& b, ex* ca, ex* cb)
1648 const ex& exp_a = a.op(1);
1650 const ex& exp_b = b.op(1);
1652 // a = p^n, b = p^m, gcd = p^min(n, m)
1653 if (p.is_equal(pb)) {
1654 if (exp_a < exp_b) {
1658 *cb = power(p, exp_b - exp_a);
1659 return power(p, exp_a);
1662 *ca = power(p, exp_a - exp_b);
1665 return power(p, exp_b);
1670 ex p_gcd = gcd(p, pb, &p_co, &pb_co, false);
1671 // a(x) = p(x)^n, b(x) = p_b(x)^m, gcd (p, p_b) = 1 ==> gcd(a,b) = 1
1672 if (p_gcd.is_equal(_ex1)) {
1678 // XXX: do I need to check for p_gcd = -1?
1681 // there are common factors:
1682 // a(x) = g(x)^n A(x)^n, b(x) = g(x)^m B(x)^m ==>
1683 // gcd(a, b) = g(x)^n gcd(A(x)^n, g(x)^(n-m) B(x)^m
1684 if (exp_a < exp_b) {
1685 ex pg = gcd(power(p_co, exp_a), power(p_gcd, exp_b-exp_a)*power(pb_co, exp_b), ca, cb, false);
1686 return power(p_gcd, exp_a)*pg;
1688 ex pg = gcd(power(p_gcd, exp_a - exp_b)*power(p_co, exp_a), power(pb_co, exp_b), ca, cb, false);
1689 return power(p_gcd, exp_b)*pg;
1693 static ex gcd_pf_pow(const ex& a, const ex& b, ex* ca, ex* cb)
1695 if (is_exactly_a<power>(a) && is_exactly_a<power>(b))
1696 return gcd_pf_pow_pow(a, b, ca, cb);
1698 if (is_exactly_a<power>(b) && (! is_exactly_a<power>(a)))
1699 return gcd_pf_pow(b, a, cb, ca);
1701 GINAC_ASSERT(is_exactly_a<power>(a));
1704 const ex& exp_a = a.op(1);
1705 if (p.is_equal(b)) {
1706 // a = p^n, b = p, gcd = p
1708 *ca = power(p, a.op(1) - 1);
1715 ex p_gcd = gcd(p, b, &p_co, &bpart_co, false);
1717 // a(x) = p(x)^n, gcd(p, b) = 1 ==> gcd(a, b) = 1
1718 if (p_gcd.is_equal(_ex1)) {
1725 // a(x) = g(x)^n A(x)^n, b(x) = g(x) B(x) ==> gcd(a, b) = g(x) gcd(g(x)^(n-1) A(x)^n, B(x))
1726 ex rg = gcd(power(p_gcd, exp_a-1)*power(p_co, exp_a), bpart_co, ca, cb, false);
1730 static ex gcd_pf_mul(const ex& a, const ex& b, ex* ca, ex* cb)
1732 if (is_exactly_a<mul>(a) && is_exactly_a<mul>(b)
1733 && (b.nops() > a.nops()))
1734 return gcd_pf_mul(b, a, cb, ca);
1736 if (is_exactly_a<mul>(b) && (!is_exactly_a<mul>(a)))
1737 return gcd_pf_mul(b, a, cb, ca);
1739 GINAC_ASSERT(is_exactly_a<mul>(a));
1740 size_t num = a.nops();
1741 exvector g; g.reserve(num);
1742 exvector acc_ca; acc_ca.reserve(num);
1744 for (size_t i=0; i<num; i++) {
1745 ex part_ca, part_cb;
1746 g.push_back(gcd(a.op(i), part_b, &part_ca, &part_cb, false));
1747 acc_ca.push_back(part_ca);
1751 *ca = (new mul(acc_ca))->setflag(status_flags::dynallocated);
1754 return (new mul(g))->setflag(status_flags::dynallocated);
1757 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1759 * @param a first multivariate polynomial
1760 * @param b second multivariate polynomial
1761 * @param check_args check whether a and b are polynomials with rational
1762 * coefficients (defaults to "true")
1763 * @return the LCM as a new expression */
1764 ex lcm(const ex &a, const ex &b, bool check_args)
1766 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b))
1767 return lcm(ex_to<numeric>(a), ex_to<numeric>(b));
1768 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
1769 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1772 ex g = gcd(a, b, &ca, &cb, false);
1778 * Square-free factorization
1781 /** Compute square-free factorization of multivariate polynomial a(x) using
1782 * Yun's algorithm. Used internally by sqrfree().
1784 * @param a multivariate polynomial over Z[X], treated here as univariate
1786 * @param x variable to factor in
1787 * @return vector of factors sorted in ascending degree */
1788 static exvector sqrfree_yun(const ex &a, const symbol &x)
1794 if (g.is_equal(_ex1)) {
1805 } while (!z.is_zero());
1810 /** Compute a square-free factorization of a multivariate polynomial in Q[X].
1812 * @param a multivariate polynomial over Q[X]
1813 * @param l lst of variables to factor in, may be left empty for autodetection
1814 * @return a square-free factorization of \p a.
1817 * A polynomial \f$p(X) \in C[X]\f$ is said <EM>square-free</EM>
1818 * if, whenever any two polynomials \f$q(X)\f$ and \f$r(X)\f$
1821 * p(X) = q(X)^2 r(X),
1823 * we have \f$q(X) \in C\f$.
1824 * This means that \f$p(X)\f$ has no repeated factors, apart
1825 * eventually from constants.
1826 * Given a polynomial \f$p(X) \in C[X]\f$, we say that the
1829 * p(X) = b \cdot p_1(X)^{a_1} \cdot p_2(X)^{a_2} \cdots p_r(X)^{a_r}
1831 * is a <EM>square-free factorization</EM> of \f$p(X)\f$ if the
1832 * following conditions hold:
1833 * -# \f$b \in C\f$ and \f$b \neq 0\f$;
1834 * -# \f$a_i\f$ is a positive integer for \f$i = 1, \ldots, r\f$;
1835 * -# the degree of the polynomial \f$p_i\f$ is strictly positive
1836 * for \f$i = 1, \ldots, r\f$;
1837 * -# the polynomial \f$\Pi_{i=1}^r p_i(X)\f$ is square-free.
1839 * Square-free factorizations need not be unique. For example, if
1840 * \f$a_i\f$ is even, we could change the polynomial \f$p_i(X)\f$
1841 * into \f$-p_i(X)\f$.
1842 * Observe also that the factors \f$p_i(X)\f$ need not be irreducible
1845 ex sqrfree(const ex &a, const lst &l)
1847 if (is_exactly_a<numeric>(a) || // algorithm does not trap a==0
1848 is_a<symbol>(a)) // shortcut
1851 // If no lst of variables to factorize in was specified we have to
1852 // invent one now. Maybe one can optimize here by reversing the order
1853 // or so, I don't know.
1857 get_symbol_stats(a, _ex0, sdv);
1858 sym_desc_vec::const_iterator it = sdv.begin(), itend = sdv.end();
1859 while (it != itend) {
1860 args.append(it->sym);
1867 // Find the symbol to factor in at this stage
1868 if (!is_a<symbol>(args.op(0)))
1869 throw (std::runtime_error("sqrfree(): invalid factorization variable"));
1870 const symbol &x = ex_to<symbol>(args.op(0));
1872 // convert the argument from something in Q[X] to something in Z[X]
1873 const numeric lcm = lcm_of_coefficients_denominators(a);
1874 const ex tmp = multiply_lcm(a,lcm);
1877 exvector factors = sqrfree_yun(tmp, x);
1879 // construct the next list of symbols with the first element popped
1881 newargs.remove_first();
1883 // recurse down the factors in remaining variables
1884 if (newargs.nops()>0) {
1885 exvector::iterator i = factors.begin();
1886 while (i != factors.end()) {
1887 *i = sqrfree(*i, newargs);
1892 // Done with recursion, now construct the final result
1894 exvector::const_iterator it = factors.begin(), itend = factors.end();
1895 for (int p = 1; it!=itend; ++it, ++p)
1896 result *= power(*it, p);
1898 // Yun's algorithm does not account for constant factors. (For univariate
1899 // polynomials it works only in the monic case.) We can correct this by
1900 // inserting what has been lost back into the result. For completeness
1901 // we'll also have to recurse down that factor in the remaining variables.
1902 if (newargs.nops()>0)
1903 result *= sqrfree(quo(tmp, result, x), newargs);
1905 result *= quo(tmp, result, x);
1907 // Put in the reational overall factor again and return
1908 return result * lcm.inverse();
1912 /** Compute square-free partial fraction decomposition of rational function
1915 * @param a rational function over Z[x], treated as univariate polynomial
1917 * @param x variable to factor in
1918 * @return decomposed rational function */
1919 ex sqrfree_parfrac(const ex & a, const symbol & x)
1921 // Find numerator and denominator
1922 ex nd = numer_denom(a);
1923 ex numer = nd.op(0), denom = nd.op(1);
1924 //clog << "numer = " << numer << ", denom = " << denom << endl;
1926 // Convert N(x)/D(x) -> Q(x) + R(x)/D(x), so degree(R) < degree(D)
1927 ex red_poly = quo(numer, denom, x), red_numer = rem(numer, denom, x).expand();
1928 //clog << "red_poly = " << red_poly << ", red_numer = " << red_numer << endl;
1930 // Factorize denominator and compute cofactors
1931 exvector yun = sqrfree_yun(denom, x);
1932 //clog << "yun factors: " << exprseq(yun) << endl;
1933 size_t num_yun = yun.size();
1934 exvector factor; factor.reserve(num_yun);
1935 exvector cofac; cofac.reserve(num_yun);
1936 for (size_t i=0; i<num_yun; i++) {
1937 if (!yun[i].is_equal(_ex1)) {
1938 for (size_t j=0; j<=i; j++) {
1939 factor.push_back(pow(yun[i], j+1));
1941 for (size_t k=0; k<num_yun; k++) {
1943 prod *= pow(yun[k], i-j);
1945 prod *= pow(yun[k], k+1);
1947 cofac.push_back(prod.expand());
1951 size_t num_factors = factor.size();
1952 //clog << "factors : " << exprseq(factor) << endl;
1953 //clog << "cofactors: " << exprseq(cofac) << endl;
1955 // Construct coefficient matrix for decomposition
1956 int max_denom_deg = denom.degree(x);
1957 matrix sys(max_denom_deg + 1, num_factors);
1958 matrix rhs(max_denom_deg + 1, 1);
1959 for (int i=0; i<=max_denom_deg; i++) {
1960 for (size_t j=0; j<num_factors; j++)
1961 sys(i, j) = cofac[j].coeff(x, i);
1962 rhs(i, 0) = red_numer.coeff(x, i);
1964 //clog << "coeffs: " << sys << endl;
1965 //clog << "rhs : " << rhs << endl;
1967 // Solve resulting linear system
1968 matrix vars(num_factors, 1);
1969 for (size_t i=0; i<num_factors; i++)
1970 vars(i, 0) = symbol();
1971 matrix sol = sys.solve(vars, rhs);
1973 // Sum up decomposed fractions
1975 for (size_t i=0; i<num_factors; i++)
1976 sum += sol(i, 0) / factor[i];
1978 return red_poly + sum;
1983 * Normal form of rational functions
1987 * Note: The internal normal() functions (= basic::normal() and overloaded
1988 * functions) all return lists of the form {numerator, denominator}. This
1989 * is to get around mul::eval()'s automatic expansion of numeric coefficients.
1990 * E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
1991 * the information that (a+b) is the numerator and 3 is the denominator.
1995 /** Create a symbol for replacing the expression "e" (or return a previously
1996 * assigned symbol). The symbol and expression are appended to repl, for
1997 * a later application of subs().
1998 * @see ex::normal */
1999 static ex replace_with_symbol(const ex & e, exmap & repl, exmap & rev_lookup)
2001 // Expression already replaced? Then return the assigned symbol
2002 exmap::const_iterator it = rev_lookup.find(e);
2003 if (it != rev_lookup.end())
2006 // Otherwise create new symbol and add to list, taking care that the
2007 // replacement expression doesn't itself contain symbols from repl,
2008 // because subs() is not recursive
2009 ex es = (new symbol)->setflag(status_flags::dynallocated);
2010 ex e_replaced = e.subs(repl, subs_options::no_pattern);
2011 repl.insert(std::make_pair(es, e_replaced));
2012 rev_lookup.insert(std::make_pair(e_replaced, es));
2016 /** Create a symbol for replacing the expression "e" (or return a previously
2017 * assigned symbol). The symbol and expression are appended to repl, and the
2018 * symbol is returned.
2019 * @see basic::to_rational
2020 * @see basic::to_polynomial */
2021 static ex replace_with_symbol(const ex & e, exmap & repl)
2023 // Expression already replaced? Then return the assigned symbol
2024 for (exmap::const_iterator it = repl.begin(); it != repl.end(); ++it)
2025 if (it->second.is_equal(e))
2028 // Otherwise create new symbol and add to list, taking care that the
2029 // replacement expression doesn't itself contain symbols from repl,
2030 // because subs() is not recursive
2031 ex es = (new symbol)->setflag(status_flags::dynallocated);
2032 ex e_replaced = e.subs(repl, subs_options::no_pattern);
2033 repl.insert(std::make_pair(es, e_replaced));
2038 /** Function object to be applied by basic::normal(). */
2039 struct normal_map_function : public map_function {
2041 normal_map_function(int l) : level(l) {}
2042 ex operator()(const ex & e) { return normal(e, level); }
2045 /** Default implementation of ex::normal(). It normalizes the children and
2046 * replaces the object with a temporary symbol.
2047 * @see ex::normal */
2048 ex basic::normal(exmap & repl, exmap & rev_lookup, int level) const
2051 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2054 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2055 else if (level == -max_recursion_level)
2056 throw(std::runtime_error("max recursion level reached"));
2058 normal_map_function map_normal(level - 1);
2059 return (new lst(replace_with_symbol(map(map_normal), repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2065 /** Implementation of ex::normal() for symbols. This returns the unmodified symbol.
2066 * @see ex::normal */
2067 ex symbol::normal(exmap & repl, exmap & rev_lookup, int level) const
2069 return (new lst(*this, _ex1))->setflag(status_flags::dynallocated);
2073 /** Implementation of ex::normal() for a numeric. It splits complex numbers
2074 * into re+I*im and replaces I and non-rational real numbers with a temporary
2076 * @see ex::normal */
2077 ex numeric::normal(exmap & repl, exmap & rev_lookup, int level) const
2079 numeric num = numer();
2082 if (num.is_real()) {
2083 if (!num.is_integer())
2084 numex = replace_with_symbol(numex, repl, rev_lookup);
2086 numeric re = num.real(), im = num.imag();
2087 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl, rev_lookup);
2088 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl, rev_lookup);
2089 numex = re_ex + im_ex * replace_with_symbol(I, repl, rev_lookup);
2092 // Denominator is always a real integer (see numeric::denom())
2093 return (new lst(numex, denom()))->setflag(status_flags::dynallocated);
2097 /** Fraction cancellation.
2098 * @param n numerator
2099 * @param d denominator
2100 * @return cancelled fraction {n, d} as a list */
2101 static ex frac_cancel(const ex &n, const ex &d)
2105 numeric pre_factor = *_num1_p;
2107 //std::clog << "frac_cancel num = " << num << ", den = " << den << std::endl;
2109 // Handle trivial case where denominator is 1
2110 if (den.is_equal(_ex1))
2111 return (new lst(num, den))->setflag(status_flags::dynallocated);
2113 // Handle special cases where numerator or denominator is 0
2115 return (new lst(num, _ex1))->setflag(status_flags::dynallocated);
2116 if (den.expand().is_zero())
2117 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
2119 // Bring numerator and denominator to Z[X] by multiplying with
2120 // LCM of all coefficients' denominators
2121 numeric num_lcm = lcm_of_coefficients_denominators(num);
2122 numeric den_lcm = lcm_of_coefficients_denominators(den);
2123 num = multiply_lcm(num, num_lcm);
2124 den = multiply_lcm(den, den_lcm);
2125 pre_factor = den_lcm / num_lcm;
2127 // Cancel GCD from numerator and denominator
2129 if (gcd(num, den, &cnum, &cden, false) != _ex1) {
2134 // Make denominator unit normal (i.e. coefficient of first symbol
2135 // as defined by get_first_symbol() is made positive)
2136 if (is_exactly_a<numeric>(den)) {
2137 if (ex_to<numeric>(den).is_negative()) {
2143 if (get_first_symbol(den, x)) {
2144 GINAC_ASSERT(is_exactly_a<numeric>(den.unit(x)));
2145 if (ex_to<numeric>(den.unit(x)).is_negative()) {
2152 // Return result as list
2153 //std::clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << std::endl;
2154 return (new lst(num * pre_factor.numer(), den * pre_factor.denom()))->setflag(status_flags::dynallocated);
2158 /** Implementation of ex::normal() for a sum. It expands terms and performs
2159 * fractional addition.
2160 * @see ex::normal */
2161 ex add::normal(exmap & repl, exmap & rev_lookup, int level) const
2164 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2165 else if (level == -max_recursion_level)
2166 throw(std::runtime_error("max recursion level reached"));
2168 // Normalize children and split each one into numerator and denominator
2169 exvector nums, dens;
2170 nums.reserve(seq.size()+1);
2171 dens.reserve(seq.size()+1);
2172 epvector::const_iterator it = seq.begin(), itend = seq.end();
2173 while (it != itend) {
2174 ex n = ex_to<basic>(recombine_pair_to_ex(*it)).normal(repl, rev_lookup, level-1);
2175 nums.push_back(n.op(0));
2176 dens.push_back(n.op(1));
2179 ex n = ex_to<numeric>(overall_coeff).normal(repl, rev_lookup, level-1);
2180 nums.push_back(n.op(0));
2181 dens.push_back(n.op(1));
2182 GINAC_ASSERT(nums.size() == dens.size());
2184 // Now, nums is a vector of all numerators and dens is a vector of
2186 //std::clog << "add::normal uses " << nums.size() << " summands:\n";
2188 // Add fractions sequentially
2189 exvector::const_iterator num_it = nums.begin(), num_itend = nums.end();
2190 exvector::const_iterator den_it = dens.begin(), den_itend = dens.end();
2191 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
2192 ex num = *num_it++, den = *den_it++;
2193 while (num_it != num_itend) {
2194 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
2195 ex next_num = *num_it++, next_den = *den_it++;
2197 // Trivially add sequences of fractions with identical denominators
2198 while ((den_it != den_itend) && next_den.is_equal(*den_it)) {
2199 next_num += *num_it;
2203 // Additiion of two fractions, taking advantage of the fact that
2204 // the heuristic GCD algorithm computes the cofactors at no extra cost
2205 ex co_den1, co_den2;
2206 ex g = gcd(den, next_den, &co_den1, &co_den2, false);
2207 num = ((num * co_den2) + (next_num * co_den1)).expand();
2208 den *= co_den2; // this is the lcm(den, next_den)
2210 //std::clog << " common denominator = " << den << std::endl;
2212 // Cancel common factors from num/den
2213 return frac_cancel(num, den);
2217 /** Implementation of ex::normal() for a product. It cancels common factors
2219 * @see ex::normal() */
2220 ex mul::normal(exmap & repl, exmap & rev_lookup, int level) const
2223 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2224 else if (level == -max_recursion_level)
2225 throw(std::runtime_error("max recursion level reached"));
2227 // Normalize children, separate into numerator and denominator
2228 exvector num; num.reserve(seq.size());
2229 exvector den; den.reserve(seq.size());
2231 epvector::const_iterator it = seq.begin(), itend = seq.end();
2232 while (it != itend) {
2233 n = ex_to<basic>(recombine_pair_to_ex(*it)).normal(repl, rev_lookup, level-1);
2234 num.push_back(n.op(0));
2235 den.push_back(n.op(1));
2238 n = ex_to<numeric>(overall_coeff).normal(repl, rev_lookup, level-1);
2239 num.push_back(n.op(0));
2240 den.push_back(n.op(1));
2242 // Perform fraction cancellation
2243 return frac_cancel((new mul(num))->setflag(status_flags::dynallocated),
2244 (new mul(den))->setflag(status_flags::dynallocated));
2248 /** Implementation of ex::normal([B) for powers. It normalizes the basis,
2249 * distributes integer exponents to numerator and denominator, and replaces
2250 * non-integer powers by temporary symbols.
2251 * @see ex::normal */
2252 ex power::normal(exmap & repl, exmap & rev_lookup, int level) const
2255 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2256 else if (level == -max_recursion_level)
2257 throw(std::runtime_error("max recursion level reached"));
2259 // Normalize basis and exponent (exponent gets reassembled)
2260 ex n_basis = ex_to<basic>(basis).normal(repl, rev_lookup, level-1);
2261 ex n_exponent = ex_to<basic>(exponent).normal(repl, rev_lookup, level-1);
2262 n_exponent = n_exponent.op(0) / n_exponent.op(1);
2264 if (n_exponent.info(info_flags::integer)) {
2266 if (n_exponent.info(info_flags::positive)) {
2268 // (a/b)^n -> {a^n, b^n}
2269 return (new lst(power(n_basis.op(0), n_exponent), power(n_basis.op(1), n_exponent)))->setflag(status_flags::dynallocated);
2271 } else if (n_exponent.info(info_flags::negative)) {
2273 // (a/b)^-n -> {b^n, a^n}
2274 return (new lst(power(n_basis.op(1), -n_exponent), power(n_basis.op(0), -n_exponent)))->setflag(status_flags::dynallocated);
2279 if (n_exponent.info(info_flags::positive)) {
2281 // (a/b)^x -> {sym((a/b)^x), 1}
2282 return (new lst(replace_with_symbol(power(n_basis.op(0) / n_basis.op(1), n_exponent), repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2284 } else if (n_exponent.info(info_flags::negative)) {
2286 if (n_basis.op(1).is_equal(_ex1)) {
2288 // a^-x -> {1, sym(a^x)}
2289 return (new lst(_ex1, replace_with_symbol(power(n_basis.op(0), -n_exponent), repl, rev_lookup)))->setflag(status_flags::dynallocated);
2293 // (a/b)^-x -> {sym((b/a)^x), 1}
2294 return (new lst(replace_with_symbol(power(n_basis.op(1) / n_basis.op(0), -n_exponent), repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2299 // (a/b)^x -> {sym((a/b)^x, 1}
2300 return (new lst(replace_with_symbol(power(n_basis.op(0) / n_basis.op(1), n_exponent), repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2304 /** Implementation of ex::normal() for pseries. It normalizes each coefficient
2305 * and replaces the series by a temporary symbol.
2306 * @see ex::normal */
2307 ex pseries::normal(exmap & repl, exmap & rev_lookup, int level) const
2310 epvector::const_iterator i = seq.begin(), end = seq.end();
2312 ex restexp = i->rest.normal();
2313 if (!restexp.is_zero())
2314 newseq.push_back(expair(restexp, i->coeff));
2317 ex n = pseries(relational(var,point), newseq);
2318 return (new lst(replace_with_symbol(n, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2322 /** Normalization of rational functions.
2323 * This function converts an expression to its normal form
2324 * "numerator/denominator", where numerator and denominator are (relatively
2325 * prime) polynomials. Any subexpressions which are not rational functions
2326 * (like non-rational numbers, non-integer powers or functions like sin(),
2327 * cos() etc.) are replaced by temporary symbols which are re-substituted by
2328 * the (normalized) subexpressions before normal() returns (this way, any
2329 * expression can be treated as a rational function). normal() is applied
2330 * recursively to arguments of functions etc.
2332 * @param level maximum depth of recursion
2333 * @return normalized expression */
2334 ex ex::normal(int level) const
2336 exmap repl, rev_lookup;
2338 ex e = bp->normal(repl, rev_lookup, level);
2339 GINAC_ASSERT(is_a<lst>(e));
2341 // Re-insert replaced symbols
2343 e = e.subs(repl, subs_options::no_pattern);
2345 // Convert {numerator, denominator} form back to fraction
2346 return e.op(0) / e.op(1);
2349 /** Get numerator of an expression. If the expression is not of the normal
2350 * form "numerator/denominator", it is first converted to this form and
2351 * then the numerator is returned.
2354 * @return numerator */
2355 ex ex::numer() const
2357 exmap repl, rev_lookup;
2359 ex e = bp->normal(repl, rev_lookup, 0);
2360 GINAC_ASSERT(is_a<lst>(e));
2362 // Re-insert replaced symbols
2366 return e.op(0).subs(repl, subs_options::no_pattern);
2369 /** Get denominator of an expression. If the expression is not of the normal
2370 * form "numerator/denominator", it is first converted to this form and
2371 * then the denominator is returned.
2374 * @return denominator */
2375 ex ex::denom() const
2377 exmap repl, rev_lookup;
2379 ex e = bp->normal(repl, rev_lookup, 0);
2380 GINAC_ASSERT(is_a<lst>(e));
2382 // Re-insert replaced symbols
2386 return e.op(1).subs(repl, subs_options::no_pattern);
2389 /** Get numerator and denominator of an expression. If the expresison is not
2390 * of the normal form "numerator/denominator", it is first converted to this
2391 * form and then a list [numerator, denominator] is returned.
2394 * @return a list [numerator, denominator] */
2395 ex ex::numer_denom() const
2397 exmap repl, rev_lookup;
2399 ex e = bp->normal(repl, rev_lookup, 0);
2400 GINAC_ASSERT(is_a<lst>(e));
2402 // Re-insert replaced symbols
2406 return e.subs(repl, subs_options::no_pattern);
2410 /** Rationalization of non-rational functions.
2411 * This function converts a general expression to a rational function
2412 * by replacing all non-rational subexpressions (like non-rational numbers,
2413 * non-integer powers or functions like sin(), cos() etc.) to temporary
2414 * symbols. This makes it possible to use functions like gcd() and divide()
2415 * on non-rational functions by applying to_rational() on the arguments,
2416 * calling the desired function and re-substituting the temporary symbols
2417 * in the result. To make the last step possible, all temporary symbols and
2418 * their associated expressions are collected in the map specified by the
2419 * repl parameter, ready to be passed as an argument to ex::subs().
2421 * @param repl collects all temporary symbols and their replacements
2422 * @return rationalized expression */
2423 ex ex::to_rational(exmap & repl) const
2425 return bp->to_rational(repl);
2428 // GiNaC 1.1 compatibility function
2429 ex ex::to_rational(lst & repl_lst) const
2431 // Convert lst to exmap
2433 for (lst::const_iterator it = repl_lst.begin(); it != repl_lst.end(); ++it)
2434 m.insert(std::make_pair(it->op(0), it->op(1)));
2436 ex ret = bp->to_rational(m);
2438 // Convert exmap back to lst
2439 repl_lst.remove_all();
2440 for (exmap::const_iterator it = m.begin(); it != m.end(); ++it)
2441 repl_lst.append(it->first == it->second);
2446 ex ex::to_polynomial(exmap & repl) const
2448 return bp->to_polynomial(repl);
2451 // GiNaC 1.1 compatibility function
2452 ex ex::to_polynomial(lst & repl_lst) const
2454 // Convert lst to exmap
2456 for (lst::const_iterator it = repl_lst.begin(); it != repl_lst.end(); ++it)
2457 m.insert(std::make_pair(it->op(0), it->op(1)));
2459 ex ret = bp->to_polynomial(m);
2461 // Convert exmap back to lst
2462 repl_lst.remove_all();
2463 for (exmap::const_iterator it = m.begin(); it != m.end(); ++it)
2464 repl_lst.append(it->first == it->second);
2469 /** Default implementation of ex::to_rational(). This replaces the object with
2470 * a temporary symbol. */
2471 ex basic::to_rational(exmap & repl) const
2473 return replace_with_symbol(*this, repl);
2476 ex basic::to_polynomial(exmap & repl) const
2478 return replace_with_symbol(*this, repl);
2482 /** Implementation of ex::to_rational() for symbols. This returns the
2483 * unmodified symbol. */
2484 ex symbol::to_rational(exmap & repl) const
2489 /** Implementation of ex::to_polynomial() for symbols. This returns the
2490 * unmodified symbol. */
2491 ex symbol::to_polynomial(exmap & repl) const
2497 /** Implementation of ex::to_rational() for a numeric. It splits complex
2498 * numbers into re+I*im and replaces I and non-rational real numbers with a
2499 * temporary symbol. */
2500 ex numeric::to_rational(exmap & repl) const
2504 return replace_with_symbol(*this, repl);
2506 numeric re = real();
2507 numeric im = imag();
2508 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl);
2509 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl);
2510 return re_ex + im_ex * replace_with_symbol(I, repl);
2515 /** Implementation of ex::to_polynomial() for a numeric. It splits complex
2516 * numbers into re+I*im and replaces I and non-integer real numbers with a
2517 * temporary symbol. */
2518 ex numeric::to_polynomial(exmap & repl) const
2522 return replace_with_symbol(*this, repl);
2524 numeric re = real();
2525 numeric im = imag();
2526 ex re_ex = re.is_integer() ? re : replace_with_symbol(re, repl);
2527 ex im_ex = im.is_integer() ? im : replace_with_symbol(im, repl);
2528 return re_ex + im_ex * replace_with_symbol(I, repl);
2534 /** Implementation of ex::to_rational() for powers. It replaces non-integer
2535 * powers by temporary symbols. */
2536 ex power::to_rational(exmap & repl) const
2538 if (exponent.info(info_flags::integer))
2539 return power(basis.to_rational(repl), exponent);
2541 return replace_with_symbol(*this, repl);
2544 /** Implementation of ex::to_polynomial() for powers. It replaces non-posint
2545 * powers by temporary symbols. */
2546 ex power::to_polynomial(exmap & repl) const
2548 if (exponent.info(info_flags::posint))
2549 return power(basis.to_rational(repl), exponent);
2550 else if (exponent.info(info_flags::negint))
2552 ex basis_pref = collect_common_factors(basis);
2553 if (is_exactly_a<mul>(basis_pref) || is_exactly_a<power>(basis_pref)) {
2554 // (A*B)^n will be automagically transformed to A^n*B^n
2555 ex t = power(basis_pref, exponent);
2556 return t.to_polynomial(repl);
2559 return power(replace_with_symbol(power(basis, _ex_1), repl), -exponent);
2562 return replace_with_symbol(*this, repl);
2566 /** Implementation of ex::to_rational() for expairseqs. */
2567 ex expairseq::to_rational(exmap & repl) const
2570 s.reserve(seq.size());
2571 epvector::const_iterator i = seq.begin(), end = seq.end();
2573 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*i).to_rational(repl)));
2576 ex oc = overall_coeff.to_rational(repl);
2577 if (oc.info(info_flags::numeric))
2578 return thisexpairseq(s, overall_coeff);
2580 s.push_back(combine_ex_with_coeff_to_pair(oc, _ex1));
2581 return thisexpairseq(s, default_overall_coeff());
2584 /** Implementation of ex::to_polynomial() for expairseqs. */
2585 ex expairseq::to_polynomial(exmap & repl) const
2588 s.reserve(seq.size());
2589 epvector::const_iterator i = seq.begin(), end = seq.end();
2591 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*i).to_polynomial(repl)));
2594 ex oc = overall_coeff.to_polynomial(repl);
2595 if (oc.info(info_flags::numeric))
2596 return thisexpairseq(s, overall_coeff);
2598 s.push_back(combine_ex_with_coeff_to_pair(oc, _ex1));
2599 return thisexpairseq(s, default_overall_coeff());
2603 /** Remove the common factor in the terms of a sum 'e' by calculating the GCD,
2604 * and multiply it into the expression 'factor' (which needs to be initialized
2605 * to 1, unless you're accumulating factors). */
2606 static ex find_common_factor(const ex & e, ex & factor, exmap & repl)
2608 if (is_exactly_a<add>(e)) {
2610 size_t num = e.nops();
2611 exvector terms; terms.reserve(num);
2614 // Find the common GCD
2615 for (size_t i=0; i<num; i++) {
2616 ex x = e.op(i).to_polynomial(repl);
2618 if (is_exactly_a<add>(x) || is_exactly_a<mul>(x) || is_a<power>(x)) {
2620 x = find_common_factor(x, f, repl);
2632 if (gc.is_equal(_ex1))
2635 // The GCD is the factor we pull out
2638 // Now divide all terms by the GCD
2639 for (size_t i=0; i<num; i++) {
2642 // Try to avoid divide() because it expands the polynomial
2644 if (is_exactly_a<mul>(t)) {
2645 for (size_t j=0; j<t.nops(); j++) {
2646 if (t.op(j).is_equal(gc)) {
2647 exvector v; v.reserve(t.nops());
2648 for (size_t k=0; k<t.nops(); k++) {
2652 v.push_back(t.op(k));
2654 t = (new mul(v))->setflag(status_flags::dynallocated);
2664 return (new add(terms))->setflag(status_flags::dynallocated);
2666 } else if (is_exactly_a<mul>(e)) {
2668 size_t num = e.nops();
2669 exvector v; v.reserve(num);
2671 for (size_t i=0; i<num; i++)
2672 v.push_back(find_common_factor(e.op(i), factor, repl));
2674 return (new mul(v))->setflag(status_flags::dynallocated);
2676 } else if (is_exactly_a<power>(e)) {
2677 const ex e_exp(e.op(1));
2678 if (e_exp.info(info_flags::integer)) {
2679 ex eb = e.op(0).to_polynomial(repl);
2680 ex factor_local(_ex1);
2681 ex pre_res = find_common_factor(eb, factor_local, repl);
2682 factor *= power(factor_local, e_exp);
2683 return power(pre_res, e_exp);
2686 return e.to_polynomial(repl);
2693 /** Collect common factors in sums. This converts expressions like
2694 * 'a*(b*x+b*y)' to 'a*b*(x+y)'. */
2695 ex collect_common_factors(const ex & e)
2697 if (is_exactly_a<add>(e) || is_exactly_a<mul>(e) || is_exactly_a<power>(e)) {
2701 ex r = find_common_factor(e, factor, repl);
2702 return factor.subs(repl, subs_options::no_pattern) * r.subs(repl, subs_options::no_pattern);
2709 /** Resultant of two expressions e1,e2 with respect to symbol s.
2710 * Method: Compute determinant of Sylvester matrix of e1,e2,s. */
2711 ex resultant(const ex & e1, const ex & e2, const ex & s)
2713 const ex ee1 = e1.expand();
2714 const ex ee2 = e2.expand();
2715 if (!ee1.info(info_flags::polynomial) ||
2716 !ee2.info(info_flags::polynomial))
2717 throw(std::runtime_error("resultant(): arguments must be polynomials"));
2719 const int h1 = ee1.degree(s);
2720 const int l1 = ee1.ldegree(s);
2721 const int h2 = ee2.degree(s);
2722 const int l2 = ee2.ldegree(s);
2724 const int msize = h1 + h2;
2725 matrix m(msize, msize);
2727 for (int l = h1; l >= l1; --l) {
2728 const ex e = ee1.coeff(s, l);
2729 for (int k = 0; k < h2; ++k)
2732 for (int l = h2; l >= l2; --l) {
2733 const ex e = ee2.coeff(s, l);
2734 for (int k = 0; k < h1; ++k)
2735 m(k+h2, k+h2-l) = e;
2738 return m.determinant();
2742 } // namespace GiNaC