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-2004 Johannes Gutenberg University Mainz, Germany
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
34 #include "expairseq.h"
41 #include "relational.h"
42 #include "operators.h"
50 // If comparing expressions (ex::compare()) is fast, you can set this to 1.
51 // Some routines like quo(), rem() and gcd() will then return a quick answer
52 // when they are called with two identical arguments.
53 #define FAST_COMPARE 1
55 // Set this if you want divide_in_z() to use remembering
56 #define USE_REMEMBER 0
58 // Set this if you want divide_in_z() to use trial division followed by
59 // polynomial interpolation (always slower except for completely dense
61 #define USE_TRIAL_DIVISION 0
63 // Set this to enable some statistical output for the GCD routines
68 // Statistics variables
69 static int gcd_called = 0;
70 static int sr_gcd_called = 0;
71 static int heur_gcd_called = 0;
72 static int heur_gcd_failed = 0;
74 // Print statistics at end of program
75 static struct _stat_print {
78 std::cout << "gcd() called " << gcd_called << " times\n";
79 std::cout << "sr_gcd() called " << sr_gcd_called << " times\n";
80 std::cout << "heur_gcd() called " << heur_gcd_called << " times\n";
81 std::cout << "heur_gcd() failed " << heur_gcd_failed << " times\n";
87 /** Return pointer to first symbol found in expression. Due to GiNaCĀ“s
88 * internal ordering of terms, it may not be obvious which symbol this
89 * function returns for a given expression.
91 * @param e expression to search
92 * @param x 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)) {
237 for (size_t i=0; i<e.nops(); i++)
238 c = lcmcoeff(e.op(i), c);
240 } else if (is_exactly_a<mul>(e)) {
242 for (size_t i=0; i<e.nops(); i++)
243 c *= lcmcoeff(e.op(i), _num1);
245 } else if (is_exactly_a<power>(e)) {
246 if (is_a<symbol>(e.op(0)))
249 return pow(lcmcoeff(e.op(0), l), ex_to<numeric>(e.op(1)));
254 /** Compute LCM of denominators of coefficients of a polynomial.
255 * Given a polynomial with rational coefficients, this function computes
256 * the LCM of the denominators of all coefficients. This can be used
257 * to bring a polynomial from Q[X] to Z[X].
259 * @param e multivariate polynomial (need not be expanded)
260 * @return LCM of denominators of coefficients */
261 static numeric lcm_of_coefficients_denominators(const ex &e)
263 return lcmcoeff(e, _num1);
266 /** Bring polynomial from Q[X] to Z[X] by multiplying in the previously
267 * determined LCM of the coefficient's denominators.
269 * @param e multivariate polynomial (need not be expanded)
270 * @param lcm LCM to multiply in */
271 static ex multiply_lcm(const ex &e, const numeric &lcm)
273 if (is_exactly_a<mul>(e)) {
274 size_t num = e.nops();
275 exvector v; v.reserve(num + 1);
276 numeric lcm_accum = _num1;
277 for (size_t i=0; i<num; i++) {
278 numeric op_lcm = lcmcoeff(e.op(i), _num1);
279 v.push_back(multiply_lcm(e.op(i), op_lcm));
282 v.push_back(lcm / lcm_accum);
283 return (new mul(v))->setflag(status_flags::dynallocated);
284 } else if (is_exactly_a<add>(e)) {
285 size_t num = e.nops();
286 exvector v; v.reserve(num);
287 for (size_t i=0; i<num; i++)
288 v.push_back(multiply_lcm(e.op(i), lcm));
289 return (new add(v))->setflag(status_flags::dynallocated);
290 } else if (is_exactly_a<power>(e)) {
291 if (is_a<symbol>(e.op(0)))
294 return pow(multiply_lcm(e.op(0), lcm.power(ex_to<numeric>(e.op(1)).inverse())), e.op(1));
300 /** Compute the integer content (= GCD of all numeric coefficients) of an
301 * expanded polynomial. 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, l = _num1;
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 // Polynomial long division (recursive)
623 int bdeg = b.degree(x);
624 int rdeg = r.degree(x);
625 ex blcoeff = b.expand().coeff(x, bdeg);
626 bool blcoeff_is_numeric = is_exactly_a<numeric>(blcoeff);
627 exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
628 while (rdeg >= bdeg) {
629 ex term, rcoeff = r.coeff(x, rdeg);
630 if (blcoeff_is_numeric)
631 term = rcoeff / blcoeff;
633 if (!divide(rcoeff, blcoeff, term, false))
635 term *= power(x, rdeg - bdeg);
637 r -= (term * b).expand();
639 q = (new add(v))->setflag(status_flags::dynallocated);
653 typedef std::pair<ex, ex> ex2;
654 typedef std::pair<ex, bool> exbool;
657 bool operator() (const ex2 &p, const ex2 &q) const
659 int cmp = p.first.compare(q.first);
660 return ((cmp<0) || (!(cmp>0) && p.second.compare(q.second)<0));
664 typedef std::map<ex2, exbool, ex2_less> ex2_exbool_remember;
668 /** Exact polynomial division of a(X) by b(X) in Z[X].
669 * This functions works like divide() but the input and output polynomials are
670 * in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
671 * divide(), it doesn't check whether the input polynomials really are integer
672 * polynomials, so be careful of what you pass in. Also, you have to run
673 * get_symbol_stats() over the input polynomials before calling this function
674 * and pass an iterator to the first element of the sym_desc vector. This
675 * function is used internally by the heur_gcd().
677 * @param a first multivariate polynomial (dividend)
678 * @param b second multivariate polynomial (divisor)
679 * @param q quotient (returned)
680 * @param var iterator to first element of vector of sym_desc structs
681 * @return "true" when exact division succeeds (the quotient is returned in
682 * q), "false" otherwise.
683 * @see get_symbol_stats, heur_gcd */
684 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
688 throw(std::overflow_error("divide_in_z: division by zero"));
689 if (b.is_equal(_ex1)) {
693 if (is_exactly_a<numeric>(a)) {
694 if (is_exactly_a<numeric>(b)) {
696 return q.info(info_flags::integer);
709 static ex2_exbool_remember dr_remember;
710 ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
711 if (remembered != dr_remember.end()) {
712 q = remembered->second.first;
713 return remembered->second.second;
718 const ex &x = var->sym;
721 int adeg = a.degree(x), bdeg = b.degree(x);
725 #if USE_TRIAL_DIVISION
727 // Trial division with polynomial interpolation
730 // Compute values at evaluation points 0..adeg
731 vector<numeric> alpha; alpha.reserve(adeg + 1);
732 exvector u; u.reserve(adeg + 1);
733 numeric point = _num0;
735 for (i=0; i<=adeg; i++) {
736 ex bs = b.subs(x == point, subs_options::no_pattern);
737 while (bs.is_zero()) {
739 bs = b.subs(x == point, subs_options::no_pattern);
741 if (!divide_in_z(a.subs(x == point, subs_options::no_pattern), bs, c, var+1))
743 alpha.push_back(point);
749 vector<numeric> rcp; rcp.reserve(adeg + 1);
750 rcp.push_back(_num0);
751 for (k=1; k<=adeg; k++) {
752 numeric product = alpha[k] - alpha[0];
754 product *= alpha[k] - alpha[i];
755 rcp.push_back(product.inverse());
758 // Compute Newton coefficients
759 exvector v; v.reserve(adeg + 1);
761 for (k=1; k<=adeg; k++) {
763 for (i=k-2; i>=0; i--)
764 temp = temp * (alpha[k] - alpha[i]) + v[i];
765 v.push_back((u[k] - temp) * rcp[k]);
768 // Convert from Newton form to standard form
770 for (k=adeg-1; k>=0; k--)
771 c = c * (x - alpha[k]) + v[k];
773 if (c.degree(x) == (adeg - bdeg)) {
781 // Polynomial long division (recursive)
787 ex blcoeff = eb.coeff(x, bdeg);
788 exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
789 while (rdeg >= bdeg) {
790 ex term, rcoeff = r.coeff(x, rdeg);
791 if (!divide_in_z(rcoeff, blcoeff, term, var+1))
793 term = (term * power(x, rdeg - bdeg)).expand();
795 r -= (term * eb).expand();
797 q = (new add(v))->setflag(status_flags::dynallocated);
799 dr_remember[ex2(a, b)] = exbool(q, true);
806 dr_remember[ex2(a, b)] = exbool(q, false);
815 * Separation of unit part, content part and primitive part of polynomials
818 /** Compute unit part (= sign of leading coefficient) of a multivariate
819 * polynomial in Q[x]. The product of unit part, content part, and primitive
820 * part is the polynomial itself.
822 * @param x main variable
824 * @see ex::content, ex::primpart, ex::unitcontprim */
825 ex ex::unit(const ex &x) const
827 ex c = expand().lcoeff(x);
828 if (is_exactly_a<numeric>(c))
829 return c.info(info_flags::negative) ?_ex_1 : _ex1;
832 if (get_first_symbol(c, y))
835 throw(std::invalid_argument("invalid expression in unit()"));
840 /** Compute content part (= unit normal GCD of all coefficients) of a
841 * multivariate polynomial in Q[x]. The product of unit part, content part,
842 * and primitive part is the polynomial itself.
844 * @param x main variable
845 * @return content part
846 * @see ex::unit, ex::primpart, ex::unitcontprim */
847 ex ex::content(const ex &x) const
849 if (is_exactly_a<numeric>(*this))
850 return info(info_flags::negative) ? -*this : *this;
856 // First, divide out the integer content (which we can calculate very efficiently).
857 // If the leading coefficient of the quotient is an integer, we are done.
858 ex c = e.integer_content();
860 int deg = r.degree(x);
861 ex lcoeff = r.coeff(x, deg);
862 if (lcoeff.info(info_flags::integer))
865 // GCD of all coefficients
866 int ldeg = r.ldegree(x);
868 return lcoeff * c / lcoeff.unit(x);
870 for (int i=ldeg; i<=deg; i++)
871 cont = gcd(r.coeff(x, i), cont, NULL, NULL, false);
876 /** Compute primitive part of a multivariate polynomial in Q[x]. The result
877 * will be a unit-normal polynomial with a content part of 1. The product
878 * of unit part, content part, and primitive part is the polynomial itself.
880 * @param x main variable
881 * @return primitive part
882 * @see ex::unit, ex::content, ex::unitcontprim */
883 ex ex::primpart(const ex &x) const
885 // We need to compute the unit and content anyway, so call unitcontprim()
887 unitcontprim(x, u, c, p);
892 /** Compute primitive part of a multivariate polynomial in Q[x] when the
893 * content part is already known. This function is faster in computing the
894 * primitive part than the previous function.
896 * @param x main variable
897 * @param c previously computed content part
898 * @return primitive part */
899 ex ex::primpart(const ex &x, const ex &c) const
901 if (is_zero() || c.is_zero())
903 if (is_exactly_a<numeric>(*this))
906 // Divide by unit and content to get primitive part
908 if (is_exactly_a<numeric>(c))
909 return *this / (c * u);
911 return quo(*this, c * u, x, false);
915 /** Compute unit part, content part, and primitive part of a multivariate
916 * polynomial in Q[x]. The product of the three parts is the polynomial
919 * @param x main variable
920 * @param u unit part (returned)
921 * @param c content part (returned)
922 * @param p primitive part (returned)
923 * @see ex::unit, ex::content, ex::primpart */
924 void ex::unitcontprim(const ex &x, ex &u, ex &c, ex &p) const
926 // Quick check for zero (avoid expanding)
933 // Special case: input is a number
934 if (is_exactly_a<numeric>(*this)) {
935 if (info(info_flags::negative)) {
937 c = abs(ex_to<numeric>(*this));
946 // Expand input polynomial
954 // Compute unit and content
958 // Divide by unit and content to get primitive part
963 if (is_exactly_a<numeric>(c))
966 p = quo(e, c * u, x, false);
971 * GCD of multivariate polynomials
974 /** Compute GCD of multivariate polynomials using the subresultant PRS
975 * algorithm. This function is used internally by gcd().
977 * @param a first multivariate polynomial
978 * @param b second multivariate polynomial
979 * @param var iterator to first element of vector of sym_desc structs
980 * @return the GCD as a new expression
983 static ex sr_gcd(const ex &a, const ex &b, sym_desc_vec::const_iterator var)
989 // The first symbol is our main variable
990 const ex &x = var->sym;
992 // Sort c and d so that c has higher degree
994 int adeg = a.degree(x), bdeg = b.degree(x);
1008 // Remove content from c and d, to be attached to GCD later
1009 ex cont_c = c.content(x);
1010 ex cont_d = d.content(x);
1011 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1014 c = c.primpart(x, cont_c);
1015 d = d.primpart(x, cont_d);
1017 // First element of subresultant sequence
1018 ex r = _ex0, ri = _ex1, psi = _ex1;
1019 int delta = cdeg - ddeg;
1023 // Calculate polynomial pseudo-remainder
1024 r = prem(c, d, x, false);
1026 return gamma * d.primpart(x);
1030 if (!divide_in_z(r, ri * pow(psi, delta), d, var))
1031 throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
1034 if (is_exactly_a<numeric>(r))
1037 return gamma * r.primpart(x);
1040 // Next element of subresultant sequence
1041 ri = c.expand().lcoeff(x);
1045 divide_in_z(pow(ri, delta), pow(psi, delta-1), psi, var+1);
1046 delta = cdeg - ddeg;
1051 /** Return maximum (absolute value) coefficient of a polynomial.
1052 * This function is used internally by heur_gcd().
1054 * @return maximum coefficient
1056 numeric ex::max_coefficient() const
1058 return bp->max_coefficient();
1061 /** Implementation ex::max_coefficient().
1063 numeric basic::max_coefficient() const
1068 numeric numeric::max_coefficient() const
1073 numeric add::max_coefficient() const
1075 epvector::const_iterator it = seq.begin();
1076 epvector::const_iterator itend = seq.end();
1077 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1078 numeric cur_max = abs(ex_to<numeric>(overall_coeff));
1079 while (it != itend) {
1081 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
1082 a = abs(ex_to<numeric>(it->coeff));
1090 numeric mul::max_coefficient() const
1092 #ifdef DO_GINAC_ASSERT
1093 epvector::const_iterator it = seq.begin();
1094 epvector::const_iterator itend = seq.end();
1095 while (it != itend) {
1096 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
1099 #endif // def DO_GINAC_ASSERT
1100 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1101 return abs(ex_to<numeric>(overall_coeff));
1105 /** Apply symmetric modular homomorphism to an expanded multivariate
1106 * polynomial. This function is usually used internally by heur_gcd().
1109 * @return mapped polynomial
1111 ex basic::smod(const numeric &xi) const
1116 ex numeric::smod(const numeric &xi) const
1118 return GiNaC::smod(*this, xi);
1121 ex add::smod(const numeric &xi) const
1124 newseq.reserve(seq.size()+1);
1125 epvector::const_iterator it = seq.begin();
1126 epvector::const_iterator itend = seq.end();
1127 while (it != itend) {
1128 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
1129 numeric coeff = GiNaC::smod(ex_to<numeric>(it->coeff), xi);
1130 if (!coeff.is_zero())
1131 newseq.push_back(expair(it->rest, coeff));
1134 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1135 numeric coeff = GiNaC::smod(ex_to<numeric>(overall_coeff), xi);
1136 return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
1139 ex mul::smod(const numeric &xi) const
1141 #ifdef DO_GINAC_ASSERT
1142 epvector::const_iterator it = seq.begin();
1143 epvector::const_iterator itend = seq.end();
1144 while (it != itend) {
1145 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
1148 #endif // def DO_GINAC_ASSERT
1149 mul * mulcopyp = new mul(*this);
1150 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1151 mulcopyp->overall_coeff = GiNaC::smod(ex_to<numeric>(overall_coeff),xi);
1152 mulcopyp->clearflag(status_flags::evaluated);
1153 mulcopyp->clearflag(status_flags::hash_calculated);
1154 return mulcopyp->setflag(status_flags::dynallocated);
1158 /** xi-adic polynomial interpolation */
1159 static ex interpolate(const ex &gamma, const numeric &xi, const ex &x, int degree_hint = 1)
1161 exvector g; g.reserve(degree_hint);
1163 numeric rxi = xi.inverse();
1164 for (int i=0; !e.is_zero(); i++) {
1166 g.push_back(gi * power(x, i));
1169 return (new add(g))->setflag(status_flags::dynallocated);
1172 /** Exception thrown by heur_gcd() to signal failure. */
1173 class gcdheu_failed {};
1175 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1176 * get_symbol_stats() must have been called previously with the input
1177 * polynomials and an iterator to the first element of the sym_desc vector
1178 * passed in. This function is used internally by gcd().
1180 * @param a first multivariate polynomial (expanded)
1181 * @param b second multivariate polynomial (expanded)
1182 * @param ca cofactor of polynomial a (returned), NULL to suppress
1183 * calculation of cofactor
1184 * @param cb cofactor of polynomial b (returned), NULL to suppress
1185 * calculation of cofactor
1186 * @param var iterator to first element of vector of sym_desc structs
1187 * @return the GCD as a new expression
1189 * @exception gcdheu_failed() */
1190 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
1196 // Algorithm only works for non-vanishing input polynomials
1197 if (a.is_zero() || b.is_zero())
1198 return (new fail())->setflag(status_flags::dynallocated);
1200 // GCD of two numeric values -> CLN
1201 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b)) {
1202 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1204 *ca = ex_to<numeric>(a) / g;
1206 *cb = ex_to<numeric>(b) / g;
1210 // The first symbol is our main variable
1211 const ex &x = var->sym;
1213 // Remove integer content
1214 numeric gc = gcd(a.integer_content(), b.integer_content());
1215 numeric rgc = gc.inverse();
1218 int maxdeg = std::max(p.degree(x), q.degree(x));
1220 // Find evaluation point
1221 numeric mp = p.max_coefficient();
1222 numeric mq = q.max_coefficient();
1225 xi = mq * _num2 + _num2;
1227 xi = mp * _num2 + _num2;
1230 for (int t=0; t<6; t++) {
1231 if (xi.int_length() * maxdeg > 100000) {
1232 throw gcdheu_failed();
1235 // Apply evaluation homomorphism and calculate GCD
1237 ex gamma = heur_gcd(p.subs(x == xi, subs_options::no_pattern), q.subs(x == xi, subs_options::no_pattern), &cp, &cq, var+1).expand();
1238 if (!is_exactly_a<fail>(gamma)) {
1240 // Reconstruct polynomial from GCD of mapped polynomials
1241 ex g = interpolate(gamma, xi, x, maxdeg);
1243 // Remove integer content
1244 g /= g.integer_content();
1246 // If the calculated polynomial divides both p and q, this is the GCD
1248 if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1250 ex lc = g.lcoeff(x);
1251 if (is_exactly_a<numeric>(lc) && ex_to<numeric>(lc).is_negative())
1258 // Next evaluation point
1259 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1261 return (new fail())->setflag(status_flags::dynallocated);
1265 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1268 * @param a first multivariate polynomial
1269 * @param b second multivariate polynomial
1270 * @param ca pointer to expression that will receive the cofactor of a, or NULL
1271 * @param cb pointer to expression that will receive the cofactor of b, or NULL
1272 * @param check_args check whether a and b are polynomials with rational
1273 * coefficients (defaults to "true")
1274 * @return the GCD as a new expression */
1275 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1281 // GCD of numerics -> CLN
1282 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b)) {
1283 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1292 *ca = ex_to<numeric>(a) / g;
1294 *cb = ex_to<numeric>(b) / g;
1301 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))) {
1302 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1305 // Partially factored cases (to avoid expanding large expressions)
1306 if (is_exactly_a<mul>(a)) {
1307 if (is_exactly_a<mul>(b) && b.nops() > a.nops())
1310 size_t num = a.nops();
1311 exvector g; g.reserve(num);
1312 exvector acc_ca; acc_ca.reserve(num);
1314 for (size_t i=0; i<num; i++) {
1315 ex part_ca, part_cb;
1316 g.push_back(gcd(a.op(i), part_b, &part_ca, &part_cb, check_args));
1317 acc_ca.push_back(part_ca);
1321 *ca = (new mul(acc_ca))->setflag(status_flags::dynallocated);
1324 return (new mul(g))->setflag(status_flags::dynallocated);
1325 } else if (is_exactly_a<mul>(b)) {
1326 if (is_exactly_a<mul>(a) && a.nops() > b.nops())
1329 size_t num = b.nops();
1330 exvector g; g.reserve(num);
1331 exvector acc_cb; acc_cb.reserve(num);
1333 for (size_t i=0; i<num; i++) {
1334 ex part_ca, part_cb;
1335 g.push_back(gcd(part_a, b.op(i), &part_ca, &part_cb, check_args));
1336 acc_cb.push_back(part_cb);
1342 *cb = (new mul(acc_cb))->setflag(status_flags::dynallocated);
1343 return (new mul(g))->setflag(status_flags::dynallocated);
1347 // Input polynomials of the form poly^n are sometimes also trivial
1348 if (is_exactly_a<power>(a)) {
1350 if (is_exactly_a<power>(b)) {
1351 if (p.is_equal(b.op(0))) {
1352 // a = p^n, b = p^m, gcd = p^min(n, m)
1353 ex exp_a = a.op(1), exp_b = b.op(1);
1354 if (exp_a < exp_b) {
1358 *cb = power(p, exp_b - exp_a);
1359 return power(p, exp_a);
1362 *ca = power(p, exp_a - exp_b);
1365 return power(p, exp_b);
1369 if (p.is_equal(b)) {
1370 // a = p^n, b = p, gcd = p
1372 *ca = power(p, a.op(1) - 1);
1378 } else if (is_exactly_a<power>(b)) {
1380 if (p.is_equal(a)) {
1381 // a = p, b = p^n, gcd = p
1385 *cb = power(p, b.op(1) - 1);
1391 // Some trivial cases
1392 ex aex = a.expand(), bex = b.expand();
1393 if (aex.is_zero()) {
1400 if (bex.is_zero()) {
1407 if (aex.is_equal(_ex1) || bex.is_equal(_ex1)) {
1415 if (a.is_equal(b)) {
1424 // Gather symbol statistics
1425 sym_desc_vec sym_stats;
1426 get_symbol_stats(a, b, sym_stats);
1428 // The symbol with least degree is our main variable
1429 sym_desc_vec::const_iterator var = sym_stats.begin();
1430 const ex &x = var->sym;
1432 // Cancel trivial common factor
1433 int ldeg_a = var->ldeg_a;
1434 int ldeg_b = var->ldeg_b;
1435 int min_ldeg = std::min(ldeg_a,ldeg_b);
1437 ex common = power(x, min_ldeg);
1438 return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1441 // Try to eliminate variables
1442 if (var->deg_a == 0) {
1443 ex bex_u, bex_c, bex_p;
1444 bex.unitcontprim(x, bex_u, bex_c, bex_p);
1445 ex g = gcd(aex, bex_c, ca, cb, false);
1447 *cb *= bex_u * bex_p;
1449 } else if (var->deg_b == 0) {
1450 ex aex_u, aex_c, aex_p;
1451 aex.unitcontprim(x, aex_u, aex_c, aex_p);
1452 ex g = gcd(aex_c, bex, ca, cb, false);
1454 *ca *= aex_u * aex_p;
1458 // Try heuristic algorithm first, fall back to PRS if that failed
1461 g = heur_gcd(aex, bex, ca, cb, var);
1462 } catch (gcdheu_failed) {
1465 if (is_exactly_a<fail>(g)) {
1469 g = sr_gcd(aex, bex, var);
1470 if (g.is_equal(_ex1)) {
1471 // Keep cofactors factored if possible
1478 divide(aex, g, *ca, false);
1480 divide(bex, g, *cb, false);
1483 if (g.is_equal(_ex1)) {
1484 // Keep cofactors factored if possible
1496 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1498 * @param a first multivariate polynomial
1499 * @param b second multivariate polynomial
1500 * @param check_args check whether a and b are polynomials with rational
1501 * coefficients (defaults to "true")
1502 * @return the LCM as a new expression */
1503 ex lcm(const ex &a, const ex &b, bool check_args)
1505 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b))
1506 return lcm(ex_to<numeric>(a), ex_to<numeric>(b));
1507 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
1508 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1511 ex g = gcd(a, b, &ca, &cb, false);
1517 * Square-free factorization
1520 /** Compute square-free factorization of multivariate polynomial a(x) using
1521 * YunĀ“s algorithm. Used internally by sqrfree().
1523 * @param a multivariate polynomial over Z[X], treated here as univariate
1525 * @param x variable to factor in
1526 * @return vector of factors sorted in ascending degree */
1527 static exvector sqrfree_yun(const ex &a, const symbol &x)
1533 if (g.is_equal(_ex1)) {
1544 } while (!z.is_zero());
1549 /** Compute a square-free factorization of a multivariate polynomial in Q[X].
1551 * @param a multivariate polynomial over Q[X]
1552 * @param l lst of variables to factor in, may be left empty for autodetection
1553 * @return a square-free factorization of \p a.
1556 * A polynomial \f$p(X) \in C[X]\f$ is said <EM>square-free</EM>
1557 * if, whenever any two polynomials \f$q(X)\f$ and \f$r(X)\f$
1560 * p(X) = q(X)^2 r(X),
1562 * we have \f$q(X) \in C\f$.
1563 * This means that \f$p(X)\f$ has no repeated factors, apart
1564 * eventually from constants.
1565 * Given a polynomial \f$p(X) \in C[X]\f$, we say that the
1568 * p(X) = b \cdot p_1(X)^{a_1} \cdot p_2(X)^{a_2} \cdots p_r(X)^{a_r}
1570 * is a <EM>square-free factorization</EM> of \f$p(X)\f$ if the
1571 * following conditions hold:
1572 * -# \f$b \in C\f$ and \f$b \neq 0\f$;
1573 * -# \f$a_i\f$ is a positive integer for \f$i = 1, \ldots, r\f$;
1574 * -# the degree of the polynomial \f$p_i\f$ is strictly positive
1575 * for \f$i = 1, \ldots, r\f$;
1576 * -# the polynomial \f$\Pi_{i=1}^r p_i(X)\f$ is square-free.
1578 * Square-free factorizations need not be unique. For example, if
1579 * \f$a_i\f$ is even, we could change the polynomial \f$p_i(X)\f$
1580 * into \f$-p_i(X)\f$.
1581 * Observe also that the factors \f$p_i(X)\f$ need not be irreducible
1584 ex sqrfree(const ex &a, const lst &l)
1586 if (is_exactly_a<numeric>(a) || // algorithm does not trap a==0
1587 is_a<symbol>(a)) // shortcut
1590 // If no lst of variables to factorize in was specified we have to
1591 // invent one now. Maybe one can optimize here by reversing the order
1592 // or so, I don't know.
1596 get_symbol_stats(a, _ex0, sdv);
1597 sym_desc_vec::const_iterator it = sdv.begin(), itend = sdv.end();
1598 while (it != itend) {
1599 args.append(it->sym);
1606 // Find the symbol to factor in at this stage
1607 if (!is_a<symbol>(args.op(0)))
1608 throw (std::runtime_error("sqrfree(): invalid factorization variable"));
1609 const symbol &x = ex_to<symbol>(args.op(0));
1611 // convert the argument from something in Q[X] to something in Z[X]
1612 const numeric lcm = lcm_of_coefficients_denominators(a);
1613 const ex tmp = multiply_lcm(a,lcm);
1616 exvector factors = sqrfree_yun(tmp, x);
1618 // construct the next list of symbols with the first element popped
1620 newargs.remove_first();
1622 // recurse down the factors in remaining variables
1623 if (newargs.nops()>0) {
1624 exvector::iterator i = factors.begin();
1625 while (i != factors.end()) {
1626 *i = sqrfree(*i, newargs);
1631 // Done with recursion, now construct the final result
1633 exvector::const_iterator it = factors.begin(), itend = factors.end();
1634 for (int p = 1; it!=itend; ++it, ++p)
1635 result *= power(*it, p);
1637 // Yun's algorithm does not account for constant factors. (For univariate
1638 // polynomials it works only in the monic case.) We can correct this by
1639 // inserting what has been lost back into the result. For completeness
1640 // we'll also have to recurse down that factor in the remaining variables.
1641 if (newargs.nops()>0)
1642 result *= sqrfree(quo(tmp, result, x), newargs);
1644 result *= quo(tmp, result, x);
1646 // Put in the reational overall factor again and return
1647 return result * lcm.inverse();
1651 /** Compute square-free partial fraction decomposition of rational function
1654 * @param a rational function over Z[x], treated as univariate polynomial
1656 * @param x variable to factor in
1657 * @return decomposed rational function */
1658 ex sqrfree_parfrac(const ex & a, const symbol & x)
1660 // Find numerator and denominator
1661 ex nd = numer_denom(a);
1662 ex numer = nd.op(0), denom = nd.op(1);
1663 //clog << "numer = " << numer << ", denom = " << denom << endl;
1665 // Convert N(x)/D(x) -> Q(x) + R(x)/D(x), so degree(R) < degree(D)
1666 ex red_poly = quo(numer, denom, x), red_numer = rem(numer, denom, x).expand();
1667 //clog << "red_poly = " << red_poly << ", red_numer = " << red_numer << endl;
1669 // Factorize denominator and compute cofactors
1670 exvector yun = sqrfree_yun(denom, x);
1671 //clog << "yun factors: " << exprseq(yun) << endl;
1672 size_t num_yun = yun.size();
1673 exvector factor; factor.reserve(num_yun);
1674 exvector cofac; cofac.reserve(num_yun);
1675 for (size_t i=0; i<num_yun; i++) {
1676 if (!yun[i].is_equal(_ex1)) {
1677 for (size_t j=0; j<=i; j++) {
1678 factor.push_back(pow(yun[i], j+1));
1680 for (size_t k=0; k<num_yun; k++) {
1682 prod *= pow(yun[k], i-j);
1684 prod *= pow(yun[k], k+1);
1686 cofac.push_back(prod.expand());
1690 size_t num_factors = factor.size();
1691 //clog << "factors : " << exprseq(factor) << endl;
1692 //clog << "cofactors: " << exprseq(cofac) << endl;
1694 // Construct coefficient matrix for decomposition
1695 int max_denom_deg = denom.degree(x);
1696 matrix sys(max_denom_deg + 1, num_factors);
1697 matrix rhs(max_denom_deg + 1, 1);
1698 for (int i=0; i<=max_denom_deg; i++) {
1699 for (size_t j=0; j<num_factors; j++)
1700 sys(i, j) = cofac[j].coeff(x, i);
1701 rhs(i, 0) = red_numer.coeff(x, i);
1703 //clog << "coeffs: " << sys << endl;
1704 //clog << "rhs : " << rhs << endl;
1706 // Solve resulting linear system
1707 matrix vars(num_factors, 1);
1708 for (size_t i=0; i<num_factors; i++)
1709 vars(i, 0) = symbol();
1710 matrix sol = sys.solve(vars, rhs);
1712 // Sum up decomposed fractions
1714 for (size_t i=0; i<num_factors; i++)
1715 sum += sol(i, 0) / factor[i];
1717 return red_poly + sum;
1722 * Normal form of rational functions
1726 * Note: The internal normal() functions (= basic::normal() and overloaded
1727 * functions) all return lists of the form {numerator, denominator}. This
1728 * is to get around mul::eval()'s automatic expansion of numeric coefficients.
1729 * E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
1730 * the information that (a+b) is the numerator and 3 is the denominator.
1734 /** Create a symbol for replacing the expression "e" (or return a previously
1735 * assigned symbol). The symbol and expression are appended to repl, for
1736 * a later application of subs().
1737 * @see ex::normal */
1738 static ex replace_with_symbol(const ex & e, exmap & repl, exmap & rev_lookup)
1740 // Expression already replaced? Then return the assigned symbol
1741 exmap::const_iterator it = rev_lookup.find(e);
1742 if (it != rev_lookup.end())
1745 // Otherwise create new symbol and add to list, taking care that the
1746 // replacement expression doesn't itself contain symbols from repl,
1747 // because subs() is not recursive
1748 ex es = (new symbol)->setflag(status_flags::dynallocated);
1749 ex e_replaced = e.subs(repl, subs_options::no_pattern);
1750 repl.insert(std::make_pair(es, e_replaced));
1751 rev_lookup.insert(std::make_pair(e_replaced, es));
1755 /** Create a symbol for replacing the expression "e" (or return a previously
1756 * assigned symbol). The symbol and expression are appended to repl, and the
1757 * symbol is returned.
1758 * @see basic::to_rational
1759 * @see basic::to_polynomial */
1760 static ex replace_with_symbol(const ex & e, exmap & repl)
1762 // Expression already replaced? Then return the assigned symbol
1763 for (exmap::const_iterator it = repl.begin(); it != repl.end(); ++it)
1764 if (it->second.is_equal(e))
1767 // Otherwise create new symbol and add to list, taking care that the
1768 // replacement expression doesn't itself contain symbols from repl,
1769 // because subs() is not recursive
1770 ex es = (new symbol)->setflag(status_flags::dynallocated);
1771 ex e_replaced = e.subs(repl, subs_options::no_pattern);
1772 repl.insert(std::make_pair(es, e_replaced));
1777 /** Function object to be applied by basic::normal(). */
1778 struct normal_map_function : public map_function {
1780 normal_map_function(int l) : level(l) {}
1781 ex operator()(const ex & e) { return normal(e, level); }
1784 /** Default implementation of ex::normal(). It normalizes the children and
1785 * replaces the object with a temporary symbol.
1786 * @see ex::normal */
1787 ex basic::normal(exmap & repl, exmap & rev_lookup, int level) const
1790 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
1793 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
1794 else if (level == -max_recursion_level)
1795 throw(std::runtime_error("max recursion level reached"));
1797 normal_map_function map_normal(level - 1);
1798 return (new lst(replace_with_symbol(map(map_normal), repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
1804 /** Implementation of ex::normal() for symbols. This returns the unmodified symbol.
1805 * @see ex::normal */
1806 ex symbol::normal(exmap & repl, exmap & rev_lookup, int level) const
1808 return (new lst(*this, _ex1))->setflag(status_flags::dynallocated);
1812 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1813 * into re+I*im and replaces I and non-rational real numbers with a temporary
1815 * @see ex::normal */
1816 ex numeric::normal(exmap & repl, exmap & rev_lookup, int level) const
1818 numeric num = numer();
1821 if (num.is_real()) {
1822 if (!num.is_integer())
1823 numex = replace_with_symbol(numex, repl, rev_lookup);
1825 numeric re = num.real(), im = num.imag();
1826 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl, rev_lookup);
1827 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl, rev_lookup);
1828 numex = re_ex + im_ex * replace_with_symbol(I, repl, rev_lookup);
1831 // Denominator is always a real integer (see numeric::denom())
1832 return (new lst(numex, denom()))->setflag(status_flags::dynallocated);
1836 /** Fraction cancellation.
1837 * @param n numerator
1838 * @param d denominator
1839 * @return cancelled fraction {n, d} as a list */
1840 static ex frac_cancel(const ex &n, const ex &d)
1844 numeric pre_factor = _num1;
1846 //std::clog << "frac_cancel num = " << num << ", den = " << den << std::endl;
1848 // Handle trivial case where denominator is 1
1849 if (den.is_equal(_ex1))
1850 return (new lst(num, den))->setflag(status_flags::dynallocated);
1852 // Handle special cases where numerator or denominator is 0
1854 return (new lst(num, _ex1))->setflag(status_flags::dynallocated);
1855 if (den.expand().is_zero())
1856 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
1858 // Bring numerator and denominator to Z[X] by multiplying with
1859 // LCM of all coefficients' denominators
1860 numeric num_lcm = lcm_of_coefficients_denominators(num);
1861 numeric den_lcm = lcm_of_coefficients_denominators(den);
1862 num = multiply_lcm(num, num_lcm);
1863 den = multiply_lcm(den, den_lcm);
1864 pre_factor = den_lcm / num_lcm;
1866 // Cancel GCD from numerator and denominator
1868 if (gcd(num, den, &cnum, &cden, false) != _ex1) {
1873 // Make denominator unit normal (i.e. coefficient of first symbol
1874 // as defined by get_first_symbol() is made positive)
1875 if (is_exactly_a<numeric>(den)) {
1876 if (ex_to<numeric>(den).is_negative()) {
1882 if (get_first_symbol(den, x)) {
1883 GINAC_ASSERT(is_exactly_a<numeric>(den.unit(x)));
1884 if (ex_to<numeric>(den.unit(x)).is_negative()) {
1891 // Return result as list
1892 //std::clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << std::endl;
1893 return (new lst(num * pre_factor.numer(), den * pre_factor.denom()))->setflag(status_flags::dynallocated);
1897 /** Implementation of ex::normal() for a sum. It expands terms and performs
1898 * fractional addition.
1899 * @see ex::normal */
1900 ex add::normal(exmap & repl, exmap & rev_lookup, int level) const
1903 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
1904 else if (level == -max_recursion_level)
1905 throw(std::runtime_error("max recursion level reached"));
1907 // Normalize children and split each one into numerator and denominator
1908 exvector nums, dens;
1909 nums.reserve(seq.size()+1);
1910 dens.reserve(seq.size()+1);
1911 epvector::const_iterator it = seq.begin(), itend = seq.end();
1912 while (it != itend) {
1913 ex n = ex_to<basic>(recombine_pair_to_ex(*it)).normal(repl, rev_lookup, level-1);
1914 nums.push_back(n.op(0));
1915 dens.push_back(n.op(1));
1918 ex n = ex_to<numeric>(overall_coeff).normal(repl, rev_lookup, level-1);
1919 nums.push_back(n.op(0));
1920 dens.push_back(n.op(1));
1921 GINAC_ASSERT(nums.size() == dens.size());
1923 // Now, nums is a vector of all numerators and dens is a vector of
1925 //std::clog << "add::normal uses " << nums.size() << " summands:\n";
1927 // Add fractions sequentially
1928 exvector::const_iterator num_it = nums.begin(), num_itend = nums.end();
1929 exvector::const_iterator den_it = dens.begin(), den_itend = dens.end();
1930 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
1931 ex num = *num_it++, den = *den_it++;
1932 while (num_it != num_itend) {
1933 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
1934 ex next_num = *num_it++, next_den = *den_it++;
1936 // Trivially add sequences of fractions with identical denominators
1937 while ((den_it != den_itend) && next_den.is_equal(*den_it)) {
1938 next_num += *num_it;
1942 // Additiion of two fractions, taking advantage of the fact that
1943 // the heuristic GCD algorithm computes the cofactors at no extra cost
1944 ex co_den1, co_den2;
1945 ex g = gcd(den, next_den, &co_den1, &co_den2, false);
1946 num = ((num * co_den2) + (next_num * co_den1)).expand();
1947 den *= co_den2; // this is the lcm(den, next_den)
1949 //std::clog << " common denominator = " << den << std::endl;
1951 // Cancel common factors from num/den
1952 return frac_cancel(num, den);
1956 /** Implementation of ex::normal() for a product. It cancels common factors
1958 * @see ex::normal() */
1959 ex mul::normal(exmap & repl, exmap & rev_lookup, int level) const
1962 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
1963 else if (level == -max_recursion_level)
1964 throw(std::runtime_error("max recursion level reached"));
1966 // Normalize children, separate into numerator and denominator
1967 exvector num; num.reserve(seq.size());
1968 exvector den; den.reserve(seq.size());
1970 epvector::const_iterator it = seq.begin(), itend = seq.end();
1971 while (it != itend) {
1972 n = ex_to<basic>(recombine_pair_to_ex(*it)).normal(repl, rev_lookup, level-1);
1973 num.push_back(n.op(0));
1974 den.push_back(n.op(1));
1977 n = ex_to<numeric>(overall_coeff).normal(repl, rev_lookup, level-1);
1978 num.push_back(n.op(0));
1979 den.push_back(n.op(1));
1981 // Perform fraction cancellation
1982 return frac_cancel((new mul(num))->setflag(status_flags::dynallocated),
1983 (new mul(den))->setflag(status_flags::dynallocated));
1987 /** Implementation of ex::normal([B) for powers. It normalizes the basis,
1988 * distributes integer exponents to numerator and denominator, and replaces
1989 * non-integer powers by temporary symbols.
1990 * @see ex::normal */
1991 ex power::normal(exmap & repl, exmap & rev_lookup, int level) const
1994 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
1995 else if (level == -max_recursion_level)
1996 throw(std::runtime_error("max recursion level reached"));
1998 // Normalize basis and exponent (exponent gets reassembled)
1999 ex n_basis = ex_to<basic>(basis).normal(repl, rev_lookup, level-1);
2000 ex n_exponent = ex_to<basic>(exponent).normal(repl, rev_lookup, level-1);
2001 n_exponent = n_exponent.op(0) / n_exponent.op(1);
2003 if (n_exponent.info(info_flags::integer)) {
2005 if (n_exponent.info(info_flags::positive)) {
2007 // (a/b)^n -> {a^n, b^n}
2008 return (new lst(power(n_basis.op(0), n_exponent), power(n_basis.op(1), n_exponent)))->setflag(status_flags::dynallocated);
2010 } else if (n_exponent.info(info_flags::negative)) {
2012 // (a/b)^-n -> {b^n, a^n}
2013 return (new lst(power(n_basis.op(1), -n_exponent), power(n_basis.op(0), -n_exponent)))->setflag(status_flags::dynallocated);
2018 if (n_exponent.info(info_flags::positive)) {
2020 // (a/b)^x -> {sym((a/b)^x), 1}
2021 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);
2023 } else if (n_exponent.info(info_flags::negative)) {
2025 if (n_basis.op(1).is_equal(_ex1)) {
2027 // a^-x -> {1, sym(a^x)}
2028 return (new lst(_ex1, replace_with_symbol(power(n_basis.op(0), -n_exponent), repl, rev_lookup)))->setflag(status_flags::dynallocated);
2032 // (a/b)^-x -> {sym((b/a)^x), 1}
2033 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);
2038 // (a/b)^x -> {sym((a/b)^x, 1}
2039 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);
2043 /** Implementation of ex::normal() for pseries. It normalizes each coefficient
2044 * and replaces the series by a temporary symbol.
2045 * @see ex::normal */
2046 ex pseries::normal(exmap & repl, exmap & rev_lookup, int level) const
2049 epvector::const_iterator i = seq.begin(), end = seq.end();
2051 ex restexp = i->rest.normal();
2052 if (!restexp.is_zero())
2053 newseq.push_back(expair(restexp, i->coeff));
2056 ex n = pseries(relational(var,point), newseq);
2057 return (new lst(replace_with_symbol(n, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2061 /** Normalization of rational functions.
2062 * This function converts an expression to its normal form
2063 * "numerator/denominator", where numerator and denominator are (relatively
2064 * prime) polynomials. Any subexpressions which are not rational functions
2065 * (like non-rational numbers, non-integer powers or functions like sin(),
2066 * cos() etc.) are replaced by temporary symbols which are re-substituted by
2067 * the (normalized) subexpressions before normal() returns (this way, any
2068 * expression can be treated as a rational function). normal() is applied
2069 * recursively to arguments of functions etc.
2071 * @param level maximum depth of recursion
2072 * @return normalized expression */
2073 ex ex::normal(int level) const
2075 exmap repl, rev_lookup;
2077 ex e = bp->normal(repl, rev_lookup, level);
2078 GINAC_ASSERT(is_a<lst>(e));
2080 // Re-insert replaced symbols
2082 e = e.subs(repl, subs_options::no_pattern);
2084 // Convert {numerator, denominator} form back to fraction
2085 return e.op(0) / e.op(1);
2088 /** Get numerator of an expression. If the expression is not of the normal
2089 * form "numerator/denominator", it is first converted to this form and
2090 * then the numerator is returned.
2093 * @return numerator */
2094 ex ex::numer() const
2096 exmap repl, rev_lookup;
2098 ex e = bp->normal(repl, rev_lookup, 0);
2099 GINAC_ASSERT(is_a<lst>(e));
2101 // Re-insert replaced symbols
2105 return e.op(0).subs(repl, subs_options::no_pattern);
2108 /** Get denominator of an expression. If the expression is not of the normal
2109 * form "numerator/denominator", it is first converted to this form and
2110 * then the denominator is returned.
2113 * @return denominator */
2114 ex ex::denom() const
2116 exmap repl, rev_lookup;
2118 ex e = bp->normal(repl, rev_lookup, 0);
2119 GINAC_ASSERT(is_a<lst>(e));
2121 // Re-insert replaced symbols
2125 return e.op(1).subs(repl, subs_options::no_pattern);
2128 /** Get numerator and denominator of an expression. If the expresison is not
2129 * of the normal form "numerator/denominator", it is first converted to this
2130 * form and then a list [numerator, denominator] is returned.
2133 * @return a list [numerator, denominator] */
2134 ex ex::numer_denom() const
2136 exmap repl, rev_lookup;
2138 ex e = bp->normal(repl, rev_lookup, 0);
2139 GINAC_ASSERT(is_a<lst>(e));
2141 // Re-insert replaced symbols
2145 return e.subs(repl, subs_options::no_pattern);
2149 /** Rationalization of non-rational functions.
2150 * This function converts a general expression to a rational function
2151 * by replacing all non-rational subexpressions (like non-rational numbers,
2152 * non-integer powers or functions like sin(), cos() etc.) to temporary
2153 * symbols. This makes it possible to use functions like gcd() and divide()
2154 * on non-rational functions by applying to_rational() on the arguments,
2155 * calling the desired function and re-substituting the temporary symbols
2156 * in the result. To make the last step possible, all temporary symbols and
2157 * their associated expressions are collected in the map specified by the
2158 * repl parameter, ready to be passed as an argument to ex::subs().
2160 * @param repl collects all temporary symbols and their replacements
2161 * @return rationalized expression */
2162 ex ex::to_rational(exmap & repl) const
2164 return bp->to_rational(repl);
2167 // GiNaC 1.1 compatibility function
2168 ex ex::to_rational(lst & repl_lst) const
2170 // Convert lst to exmap
2172 for (lst::const_iterator it = repl_lst.begin(); it != repl_lst.end(); ++it)
2173 m.insert(std::make_pair(it->op(0), it->op(1)));
2175 ex ret = bp->to_rational(m);
2177 // Convert exmap back to lst
2178 repl_lst.remove_all();
2179 for (exmap::const_iterator it = m.begin(); it != m.end(); ++it)
2180 repl_lst.append(it->first == it->second);
2185 ex ex::to_polynomial(exmap & repl) const
2187 return bp->to_polynomial(repl);
2190 // GiNaC 1.1 compatibility function
2191 ex ex::to_polynomial(lst & repl_lst) const
2193 // Convert lst to exmap
2195 for (lst::const_iterator it = repl_lst.begin(); it != repl_lst.end(); ++it)
2196 m.insert(std::make_pair(it->op(0), it->op(1)));
2198 ex ret = bp->to_polynomial(m);
2200 // Convert exmap back to lst
2201 repl_lst.remove_all();
2202 for (exmap::const_iterator it = m.begin(); it != m.end(); ++it)
2203 repl_lst.append(it->first == it->second);
2208 /** Default implementation of ex::to_rational(). This replaces the object with
2209 * a temporary symbol. */
2210 ex basic::to_rational(exmap & repl) const
2212 return replace_with_symbol(*this, repl);
2215 ex basic::to_polynomial(exmap & repl) const
2217 return replace_with_symbol(*this, repl);
2221 /** Implementation of ex::to_rational() for symbols. This returns the
2222 * unmodified symbol. */
2223 ex symbol::to_rational(exmap & repl) const
2228 /** Implementation of ex::to_polynomial() for symbols. This returns the
2229 * unmodified symbol. */
2230 ex symbol::to_polynomial(exmap & repl) const
2236 /** Implementation of ex::to_rational() for a numeric. It splits complex
2237 * numbers into re+I*im and replaces I and non-rational real numbers with a
2238 * temporary symbol. */
2239 ex numeric::to_rational(exmap & repl) const
2243 return replace_with_symbol(*this, repl);
2245 numeric re = real();
2246 numeric im = imag();
2247 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl);
2248 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl);
2249 return re_ex + im_ex * replace_with_symbol(I, repl);
2254 /** Implementation of ex::to_polynomial() for a numeric. It splits complex
2255 * numbers into re+I*im and replaces I and non-integer real numbers with a
2256 * temporary symbol. */
2257 ex numeric::to_polynomial(exmap & repl) const
2261 return replace_with_symbol(*this, repl);
2263 numeric re = real();
2264 numeric im = imag();
2265 ex re_ex = re.is_integer() ? re : replace_with_symbol(re, repl);
2266 ex im_ex = im.is_integer() ? im : replace_with_symbol(im, repl);
2267 return re_ex + im_ex * replace_with_symbol(I, repl);
2273 /** Implementation of ex::to_rational() for powers. It replaces non-integer
2274 * powers by temporary symbols. */
2275 ex power::to_rational(exmap & repl) const
2277 if (exponent.info(info_flags::integer))
2278 return power(basis.to_rational(repl), exponent);
2280 return replace_with_symbol(*this, repl);
2283 /** Implementation of ex::to_polynomial() for powers. It replaces non-posint
2284 * powers by temporary symbols. */
2285 ex power::to_polynomial(exmap & repl) const
2287 if (exponent.info(info_flags::posint))
2288 return power(basis.to_rational(repl), exponent);
2290 return replace_with_symbol(*this, repl);
2294 /** Implementation of ex::to_rational() for expairseqs. */
2295 ex expairseq::to_rational(exmap & repl) const
2298 s.reserve(seq.size());
2299 epvector::const_iterator i = seq.begin(), end = seq.end();
2301 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*i).to_rational(repl)));
2304 ex oc = overall_coeff.to_rational(repl);
2305 if (oc.info(info_flags::numeric))
2306 return thisexpairseq(s, overall_coeff);
2308 s.push_back(combine_ex_with_coeff_to_pair(oc, _ex1));
2309 return thisexpairseq(s, default_overall_coeff());
2312 /** Implementation of ex::to_polynomial() for expairseqs. */
2313 ex expairseq::to_polynomial(exmap & repl) const
2316 s.reserve(seq.size());
2317 epvector::const_iterator i = seq.begin(), end = seq.end();
2319 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*i).to_polynomial(repl)));
2322 ex oc = overall_coeff.to_polynomial(repl);
2323 if (oc.info(info_flags::numeric))
2324 return thisexpairseq(s, overall_coeff);
2326 s.push_back(combine_ex_with_coeff_to_pair(oc, _ex1));
2327 return thisexpairseq(s, default_overall_coeff());
2331 /** Remove the common factor in the terms of a sum 'e' by calculating the GCD,
2332 * and multiply it into the expression 'factor' (which needs to be initialized
2333 * to 1, unless you're accumulating factors). */
2334 static ex find_common_factor(const ex & e, ex & factor, exmap & repl)
2336 if (is_exactly_a<add>(e)) {
2338 size_t num = e.nops();
2339 exvector terms; terms.reserve(num);
2342 // Find the common GCD
2343 for (size_t i=0; i<num; i++) {
2344 ex x = e.op(i).to_polynomial(repl);
2346 if (is_exactly_a<add>(x) || is_exactly_a<mul>(x)) {
2348 x = find_common_factor(x, f, repl);
2360 if (gc.is_equal(_ex1))
2363 // The GCD is the factor we pull out
2366 // Now divide all terms by the GCD
2367 for (size_t i=0; i<num; i++) {
2370 // Try to avoid divide() because it expands the polynomial
2372 if (is_exactly_a<mul>(t)) {
2373 for (size_t j=0; j<t.nops(); j++) {
2374 if (t.op(j).is_equal(gc)) {
2375 exvector v; v.reserve(t.nops());
2376 for (size_t k=0; k<t.nops(); k++) {
2380 v.push_back(t.op(k));
2382 t = (new mul(v))->setflag(status_flags::dynallocated);
2392 return (new add(terms))->setflag(status_flags::dynallocated);
2394 } else if (is_exactly_a<mul>(e)) {
2396 size_t num = e.nops();
2397 exvector v; v.reserve(num);
2399 for (size_t i=0; i<num; i++)
2400 v.push_back(find_common_factor(e.op(i), factor, repl));
2402 return (new mul(v))->setflag(status_flags::dynallocated);
2404 } else if (is_exactly_a<power>(e)) {
2406 return e.to_polynomial(repl);
2413 /** Collect common factors in sums. This converts expressions like
2414 * 'a*(b*x+b*y)' to 'a*b*(x+y)'. */
2415 ex collect_common_factors(const ex & e)
2417 if (is_exactly_a<add>(e) || is_exactly_a<mul>(e)) {
2421 ex r = find_common_factor(e, factor, repl);
2422 return factor.subs(repl, subs_options::no_pattern) * r.subs(repl, subs_options::no_pattern);
2429 /** Resultant of two expressions e1,e2 with respect to symbol s.
2430 * Method: Compute determinant of Sylvester matrix of e1,e2,s. */
2431 ex resultant(const ex & e1, const ex & e2, const ex & s)
2433 const ex ee1 = e1.expand();
2434 const ex ee2 = e2.expand();
2435 if (!ee1.info(info_flags::polynomial) ||
2436 !ee2.info(info_flags::polynomial))
2437 throw(std::runtime_error("resultant(): arguments must be polynomials"));
2439 const int h1 = ee1.degree(s);
2440 const int l1 = ee1.ldegree(s);
2441 const int h2 = ee2.degree(s);
2442 const int l2 = ee2.ldegree(s);
2444 const int msize = h1 + h2;
2445 matrix m(msize, msize);
2447 for (int l = h1; l >= l1; --l) {
2448 const ex e = ee1.coeff(s, l);
2449 for (int k = 0; k < h2; ++k)
2452 for (int l = h2; l >= l2; --l) {
2453 const ex e = ee2.coeff(s, l);
2454 for (int k = 0; k < h1; ++k)
2455 m(k+h2, k+h2-l) = e;
2458 return m.determinant();
2462 } // namespace GiNaC