3 * This file implements several functions that work on univariate and
4 * multivariate polynomials and rational functions.
5 * These functions include polynomial quotient and remainder, GCD and LCM
6 * computation, square-free factorization and rational function normalization. */
9 * GiNaC Copyright (C) 1999-2003 Johannes Gutenberg University Mainz, Germany
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
34 #include "expairseq.h"
41 #include "relational.h"
42 #include "operators.h"
50 // If comparing expressions (ex::compare()) is fast, you can set this to 1.
51 // Some routines like quo(), rem() and gcd() will then return a quick answer
52 // when they are called with two identical arguments.
53 #define FAST_COMPARE 1
55 // Set this if you want divide_in_z() to use remembering
56 #define USE_REMEMBER 0
58 // Set this if you want divide_in_z() to use trial division followed by
59 // polynomial interpolation (always slower except for completely dense
61 #define USE_TRIAL_DIVISION 0
63 // Set this to enable some statistical output for the GCD routines
68 // Statistics variables
69 static int gcd_called = 0;
70 static int sr_gcd_called = 0;
71 static int heur_gcd_called = 0;
72 static int heur_gcd_failed = 0;
74 // Print statistics at end of program
75 static struct _stat_print {
78 std::cout << "gcd() called " << gcd_called << " times\n";
79 std::cout << "sr_gcd() called " << sr_gcd_called << " times\n";
80 std::cout << "heur_gcd() called " << heur_gcd_called << " times\n";
81 std::cout << "heur_gcd() failed " << heur_gcd_failed << " times\n";
87 /** Return pointer to first symbol found in expression. Due to GiNaCĀ“s
88 * internal ordering of terms, it may not be obvious which symbol this
89 * function returns for a given expression.
91 * @param e expression to search
92 * @param x pointer to first symbol found (returned)
93 * @return "false" if no symbol was found, "true" otherwise */
94 static bool get_first_symbol(const ex &e, const symbol *&x)
96 if (is_a<symbol>(e)) {
97 x = &ex_to<symbol>(e);
99 } else if (is_exactly_a<add>(e) || is_exactly_a<mul>(e)) {
100 for (size_t i=0; i<e.nops(); i++)
101 if (get_first_symbol(e.op(i), x))
103 } else if (is_exactly_a<power>(e)) {
104 if (get_first_symbol(e.op(0), x))
112 * Statistical information about symbols in polynomials
115 /** This structure holds information about the highest and lowest degrees
116 * in which a symbol appears in two multivariate polynomials "a" and "b".
117 * A vector of these structures with information about all symbols in
118 * two polynomials can be created with the function get_symbol_stats().
120 * @see get_symbol_stats */
122 /** Pointer to symbol */
125 /** Highest degree of symbol in polynomial "a" */
128 /** Highest degree of symbol in polynomial "b" */
131 /** Lowest degree of symbol in polynomial "a" */
134 /** Lowest degree of symbol in polynomial "b" */
137 /** Maximum of deg_a and deg_b (Used for sorting) */
140 /** Maximum number of terms of leading coefficient of symbol in both polynomials */
143 /** Commparison operator for sorting */
144 bool operator<(const sym_desc &x) const
146 if (max_deg == x.max_deg)
147 return max_lcnops < x.max_lcnops;
149 return max_deg < x.max_deg;
153 // Vector of sym_desc structures
154 typedef std::vector<sym_desc> sym_desc_vec;
156 // Add symbol the sym_desc_vec (used internally by get_symbol_stats())
157 static void add_symbol(const symbol *s, sym_desc_vec &v)
159 sym_desc_vec::const_iterator it = v.begin(), itend = v.end();
160 while (it != itend) {
161 if (it->sym->compare(*s) == 0) // If it's already in there, don't add it a second time
170 // Collect all symbols of an expression (used internally by get_symbol_stats())
171 static void collect_symbols(const ex &e, sym_desc_vec &v)
173 if (is_a<symbol>(e)) {
174 add_symbol(&ex_to<symbol>(e), v);
175 } else if (is_exactly_a<add>(e) || is_exactly_a<mul>(e)) {
176 for (size_t i=0; i<e.nops(); i++)
177 collect_symbols(e.op(i), v);
178 } else if (is_exactly_a<power>(e)) {
179 collect_symbols(e.op(0), v);
183 /** Collect statistical information about symbols in polynomials.
184 * This function fills in a vector of "sym_desc" structs which contain
185 * information about the highest and lowest degrees of all symbols that
186 * appear in two polynomials. The vector is then sorted by minimum
187 * degree (lowest to highest). The information gathered by this
188 * function is used by the GCD routines to identify trivial factors
189 * and to determine which variable to choose as the main variable
190 * for GCD computation.
192 * @param a first multivariate polynomial
193 * @param b second multivariate polynomial
194 * @param v vector of sym_desc structs (filled in) */
195 static void get_symbol_stats(const ex &a, const ex &b, sym_desc_vec &v)
197 collect_symbols(a.eval(), v); // eval() to expand assigned symbols
198 collect_symbols(b.eval(), v);
199 sym_desc_vec::iterator it = v.begin(), itend = v.end();
200 while (it != itend) {
201 int deg_a = a.degree(*(it->sym));
202 int deg_b = b.degree(*(it->sym));
205 it->max_deg = std::max(deg_a, deg_b);
206 it->max_lcnops = std::max(a.lcoeff(*(it->sym)).nops(), b.lcoeff(*(it->sym)).nops());
207 it->ldeg_a = a.ldegree(*(it->sym));
208 it->ldeg_b = b.ldegree(*(it->sym));
211 std::sort(v.begin(), v.end());
214 std::clog << "Symbols:\n";
215 it = v.begin(); itend = v.end();
216 while (it != itend) {
217 std::clog << " " << *it->sym << ": deg_a=" << it->deg_a << ", deg_b=" << it->deg_b << ", ldeg_a=" << it->ldeg_a << ", ldeg_b=" << it->ldeg_b << ", max_deg=" << it->max_deg << ", max_lcnops=" << it->max_lcnops << endl;
218 std::clog << " lcoeff_a=" << a.lcoeff(*(it->sym)) << ", lcoeff_b=" << b.lcoeff(*(it->sym)) << endl;
226 * Computation of LCM of denominators of coefficients of a polynomial
229 // Compute LCM of denominators of coefficients by going through the
230 // expression recursively (used internally by lcm_of_coefficients_denominators())
231 static numeric lcmcoeff(const ex &e, const numeric &l)
233 if (e.info(info_flags::rational))
234 return lcm(ex_to<numeric>(e).denom(), l);
235 else if (is_exactly_a<add>(e)) {
237 for (size_t i=0; i<e.nops(); i++)
238 c = lcmcoeff(e.op(i), c);
240 } else if (is_exactly_a<mul>(e)) {
242 for (size_t i=0; i<e.nops(); i++)
243 c *= lcmcoeff(e.op(i), _num1);
245 } else if (is_exactly_a<power>(e)) {
246 if (is_a<symbol>(e.op(0)))
249 return pow(lcmcoeff(e.op(0), l), ex_to<numeric>(e.op(1)));
254 /** Compute LCM of denominators of coefficients of a polynomial.
255 * Given a polynomial with rational coefficients, this function computes
256 * the LCM of the denominators of all coefficients. This can be used
257 * to bring a polynomial from Q[X] to Z[X].
259 * @param e multivariate polynomial (need not be expanded)
260 * @return LCM of denominators of coefficients */
261 static numeric lcm_of_coefficients_denominators(const ex &e)
263 return lcmcoeff(e, _num1);
266 /** Bring polynomial from Q[X] to Z[X] by multiplying in the previously
267 * determined LCM of the coefficient's denominators.
269 * @param e multivariate polynomial (need not be expanded)
270 * @param lcm LCM to multiply in */
271 static ex multiply_lcm(const ex &e, const numeric &lcm)
273 if (is_exactly_a<mul>(e)) {
274 size_t num = e.nops();
275 exvector v; v.reserve(num + 1);
276 numeric lcm_accum = _num1;
277 for (size_t i=0; i<num; i++) {
278 numeric op_lcm = lcmcoeff(e.op(i), _num1);
279 v.push_back(multiply_lcm(e.op(i), op_lcm));
282 v.push_back(lcm / lcm_accum);
283 return (new mul(v))->setflag(status_flags::dynallocated);
284 } else if (is_exactly_a<add>(e)) {
285 size_t num = e.nops();
286 exvector v; v.reserve(num);
287 for (size_t i=0; i<num; i++)
288 v.push_back(multiply_lcm(e.op(i), lcm));
289 return (new add(v))->setflag(status_flags::dynallocated);
290 } else if (is_exactly_a<power>(e)) {
291 if (is_a<symbol>(e.op(0)))
294 return pow(multiply_lcm(e.op(0), lcm.power(ex_to<numeric>(e.op(1)).inverse())), e.op(1));
300 /** Compute the integer content (= GCD of all numeric coefficients) of an
301 * expanded polynomial.
303 * @param e expanded polynomial
304 * @return integer content */
305 numeric ex::integer_content() const
307 return bp->integer_content();
310 numeric basic::integer_content() const
315 numeric numeric::integer_content() const
320 numeric add::integer_content() const
322 epvector::const_iterator it = seq.begin();
323 epvector::const_iterator itend = seq.end();
325 while (it != itend) {
326 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
327 GINAC_ASSERT(is_exactly_a<numeric>(it->coeff));
328 c = gcd(ex_to<numeric>(it->coeff), c);
331 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
332 c = gcd(ex_to<numeric>(overall_coeff),c);
336 numeric mul::integer_content() const
338 #ifdef DO_GINAC_ASSERT
339 epvector::const_iterator it = seq.begin();
340 epvector::const_iterator itend = seq.end();
341 while (it != itend) {
342 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
345 #endif // def DO_GINAC_ASSERT
346 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
347 return abs(ex_to<numeric>(overall_coeff));
352 * Polynomial quotients and remainders
355 /** Quotient q(x) of polynomials a(x) and b(x) in Q[x].
356 * It satisfies a(x)=b(x)*q(x)+r(x).
358 * @param a first polynomial in x (dividend)
359 * @param b second polynomial in x (divisor)
360 * @param x a and b are polynomials in x
361 * @param check_args check whether a and b are polynomials with rational
362 * coefficients (defaults to "true")
363 * @return quotient of a and b in Q[x] */
364 ex quo(const ex &a, const ex &b, const symbol &x, bool check_args)
367 throw(std::overflow_error("quo: division by zero"));
368 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b))
374 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
375 throw(std::invalid_argument("quo: arguments must be polynomials over the rationals"));
377 // Polynomial long division
381 int bdeg = b.degree(x);
382 int rdeg = r.degree(x);
383 ex blcoeff = b.expand().coeff(x, bdeg);
384 bool blcoeff_is_numeric = is_exactly_a<numeric>(blcoeff);
385 exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
386 while (rdeg >= bdeg) {
387 ex term, rcoeff = r.coeff(x, rdeg);
388 if (blcoeff_is_numeric)
389 term = rcoeff / blcoeff;
391 if (!divide(rcoeff, blcoeff, term, false))
392 return (new fail())->setflag(status_flags::dynallocated);
394 term *= power(x, rdeg - bdeg);
396 r -= (term * b).expand();
401 return (new add(v))->setflag(status_flags::dynallocated);
405 /** Remainder r(x) of polynomials a(x) and b(x) in Q[x].
406 * It satisfies a(x)=b(x)*q(x)+r(x).
408 * @param a first polynomial in x (dividend)
409 * @param b second polynomial in x (divisor)
410 * @param x a and b are polynomials in x
411 * @param check_args check whether a and b are polynomials with rational
412 * coefficients (defaults to "true")
413 * @return remainder of a(x) and b(x) in Q[x] */
414 ex rem(const ex &a, const ex &b, const symbol &x, bool check_args)
417 throw(std::overflow_error("rem: division by zero"));
418 if (is_exactly_a<numeric>(a)) {
419 if (is_exactly_a<numeric>(b))
428 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
429 throw(std::invalid_argument("rem: arguments must be polynomials over the rationals"));
431 // Polynomial long division
435 int bdeg = b.degree(x);
436 int rdeg = r.degree(x);
437 ex blcoeff = b.expand().coeff(x, bdeg);
438 bool blcoeff_is_numeric = is_exactly_a<numeric>(blcoeff);
439 while (rdeg >= bdeg) {
440 ex term, rcoeff = r.coeff(x, rdeg);
441 if (blcoeff_is_numeric)
442 term = rcoeff / blcoeff;
444 if (!divide(rcoeff, blcoeff, term, false))
445 return (new fail())->setflag(status_flags::dynallocated);
447 term *= power(x, rdeg - bdeg);
448 r -= (term * b).expand();
457 /** Decompose rational function a(x)=N(x)/D(x) into P(x)+n(x)/D(x)
458 * with degree(n, x) < degree(D, x).
460 * @param a rational function in x
461 * @param x a is a function of x
462 * @return decomposed function. */
463 ex decomp_rational(const ex &a, const symbol &x)
465 ex nd = numer_denom(a);
466 ex numer = nd.op(0), denom = nd.op(1);
467 ex q = quo(numer, denom, x);
468 if (is_exactly_a<fail>(q))
471 return q + rem(numer, denom, x) / denom;
475 /** Pseudo-remainder of polynomials a(x) and b(x) in Q[x].
477 * @param a first polynomial in x (dividend)
478 * @param b second polynomial in x (divisor)
479 * @param x a and b are polynomials in x
480 * @param check_args check whether a and b are polynomials with rational
481 * coefficients (defaults to "true")
482 * @return pseudo-remainder of a(x) and b(x) in Q[x] */
483 ex prem(const ex &a, const ex &b, const symbol &x, bool check_args)
486 throw(std::overflow_error("prem: division by zero"));
487 if (is_exactly_a<numeric>(a)) {
488 if (is_exactly_a<numeric>(b))
493 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
494 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
496 // Polynomial long division
499 int rdeg = r.degree(x);
500 int bdeg = eb.degree(x);
503 blcoeff = eb.coeff(x, bdeg);
507 eb -= blcoeff * power(x, bdeg);
511 int delta = rdeg - bdeg + 1, i = 0;
512 while (rdeg >= bdeg && !r.is_zero()) {
513 ex rlcoeff = r.coeff(x, rdeg);
514 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
518 r -= rlcoeff * power(x, rdeg);
519 r = (blcoeff * r).expand() - term;
523 return power(blcoeff, delta - i) * r;
527 /** Sparse pseudo-remainder of polynomials a(x) and b(x) in Q[x].
529 * @param a first polynomial in x (dividend)
530 * @param b second polynomial in x (divisor)
531 * @param x a and b are polynomials in x
532 * @param check_args check whether a and b are polynomials with rational
533 * coefficients (defaults to "true")
534 * @return sparse pseudo-remainder of a(x) and b(x) in Q[x] */
535 ex sprem(const ex &a, const ex &b, const symbol &x, bool check_args)
538 throw(std::overflow_error("prem: division by zero"));
539 if (is_exactly_a<numeric>(a)) {
540 if (is_exactly_a<numeric>(b))
545 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
546 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
548 // Polynomial long division
551 int rdeg = r.degree(x);
552 int bdeg = eb.degree(x);
555 blcoeff = eb.coeff(x, bdeg);
559 eb -= blcoeff * power(x, bdeg);
563 while (rdeg >= bdeg && !r.is_zero()) {
564 ex rlcoeff = r.coeff(x, rdeg);
565 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
569 r -= rlcoeff * power(x, rdeg);
570 r = (blcoeff * r).expand() - term;
577 /** Exact polynomial division of a(X) by b(X) in Q[X].
579 * @param a first multivariate polynomial (dividend)
580 * @param b second multivariate polynomial (divisor)
581 * @param q quotient (returned)
582 * @param check_args check whether a and b are polynomials with rational
583 * coefficients (defaults to "true")
584 * @return "true" when exact division succeeds (quotient returned in q),
585 * "false" otherwise (q left untouched) */
586 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
589 throw(std::overflow_error("divide: division by zero"));
594 if (is_exactly_a<numeric>(b)) {
597 } else if (is_exactly_a<numeric>(a))
605 if (check_args && (!a.info(info_flags::rational_polynomial) ||
606 !b.info(info_flags::rational_polynomial)))
607 throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
611 if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
612 throw(std::invalid_argument("invalid expression in divide()"));
614 // Polynomial long division (recursive)
620 int bdeg = b.degree(*x);
621 int rdeg = r.degree(*x);
622 ex blcoeff = b.expand().coeff(*x, bdeg);
623 bool blcoeff_is_numeric = is_exactly_a<numeric>(blcoeff);
624 exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
625 while (rdeg >= bdeg) {
626 ex term, rcoeff = r.coeff(*x, rdeg);
627 if (blcoeff_is_numeric)
628 term = rcoeff / blcoeff;
630 if (!divide(rcoeff, blcoeff, term, false))
632 term *= power(*x, rdeg - bdeg);
634 r -= (term * b).expand();
636 q = (new add(v))->setflag(status_flags::dynallocated);
650 typedef std::pair<ex, ex> ex2;
651 typedef std::pair<ex, bool> exbool;
654 bool operator() (const ex2 &p, const ex2 &q) const
656 int cmp = p.first.compare(q.first);
657 return ((cmp<0) || (!(cmp>0) && p.second.compare(q.second)<0));
661 typedef std::map<ex2, exbool, ex2_less> ex2_exbool_remember;
665 /** Exact polynomial division of a(X) by b(X) in Z[X].
666 * This functions works like divide() but the input and output polynomials are
667 * in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
668 * divide(), it doesnĀ“t check whether the input polynomials really are integer
669 * polynomials, so be careful of what you pass in. Also, you have to run
670 * get_symbol_stats() over the input polynomials before calling this function
671 * and pass an iterator to the first element of the sym_desc vector. This
672 * function is used internally by the heur_gcd().
674 * @param a first multivariate polynomial (dividend)
675 * @param b second multivariate polynomial (divisor)
676 * @param q quotient (returned)
677 * @param var iterator to first element of vector of sym_desc structs
678 * @return "true" when exact division succeeds (the quotient is returned in
679 * q), "false" otherwise.
680 * @see get_symbol_stats, heur_gcd */
681 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
685 throw(std::overflow_error("divide_in_z: division by zero"));
686 if (b.is_equal(_ex1)) {
690 if (is_exactly_a<numeric>(a)) {
691 if (is_exactly_a<numeric>(b)) {
693 return q.info(info_flags::integer);
706 static ex2_exbool_remember dr_remember;
707 ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
708 if (remembered != dr_remember.end()) {
709 q = remembered->second.first;
710 return remembered->second.second;
715 const symbol *x = var->sym;
718 int adeg = a.degree(*x), bdeg = b.degree(*x);
722 #if USE_TRIAL_DIVISION
724 // Trial division with polynomial interpolation
727 // Compute values at evaluation points 0..adeg
728 vector<numeric> alpha; alpha.reserve(adeg + 1);
729 exvector u; u.reserve(adeg + 1);
730 numeric point = _num0;
732 for (i=0; i<=adeg; i++) {
733 ex bs = b.subs(*x == point, subs_options::no_pattern);
734 while (bs.is_zero()) {
736 bs = b.subs(*x == point, subs_options::no_pattern);
738 if (!divide_in_z(a.subs(*x == point, subs_options::no_pattern), bs, c, var+1))
740 alpha.push_back(point);
746 vector<numeric> rcp; rcp.reserve(adeg + 1);
747 rcp.push_back(_num0);
748 for (k=1; k<=adeg; k++) {
749 numeric product = alpha[k] - alpha[0];
751 product *= alpha[k] - alpha[i];
752 rcp.push_back(product.inverse());
755 // Compute Newton coefficients
756 exvector v; v.reserve(adeg + 1);
758 for (k=1; k<=adeg; k++) {
760 for (i=k-2; i>=0; i--)
761 temp = temp * (alpha[k] - alpha[i]) + v[i];
762 v.push_back((u[k] - temp) * rcp[k]);
765 // Convert from Newton form to standard form
767 for (k=adeg-1; k>=0; k--)
768 c = c * (*x - alpha[k]) + v[k];
770 if (c.degree(*x) == (adeg - bdeg)) {
778 // Polynomial long division (recursive)
784 ex blcoeff = eb.coeff(*x, bdeg);
785 exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
786 while (rdeg >= bdeg) {
787 ex term, rcoeff = r.coeff(*x, rdeg);
788 if (!divide_in_z(rcoeff, blcoeff, term, var+1))
790 term = (term * power(*x, rdeg - bdeg)).expand();
792 r -= (term * eb).expand();
794 q = (new add(v))->setflag(status_flags::dynallocated);
796 dr_remember[ex2(a, b)] = exbool(q, true);
803 dr_remember[ex2(a, b)] = exbool(q, false);
812 * Separation of unit part, content part and primitive part of polynomials
815 /** Compute unit part (= sign of leading coefficient) of a multivariate
816 * polynomial in Z[x]. The product of unit part, content part, and primitive
817 * part is the polynomial itself.
819 * @param x variable in which to compute the unit part
821 * @see ex::content, ex::primpart */
822 ex ex::unit(const symbol &x) const
824 ex c = expand().lcoeff(x);
825 if (is_exactly_a<numeric>(c))
826 return c < _ex0 ? _ex_1 : _ex1;
829 if (get_first_symbol(c, y))
832 throw(std::invalid_argument("invalid expression in unit()"));
837 /** Compute content part (= unit normal GCD of all coefficients) of a
838 * multivariate polynomial in Z[x]. The product of unit part, content part,
839 * and primitive part is the polynomial itself.
841 * @param x variable in which to compute the content part
842 * @return content part
843 * @see ex::unit, ex::primpart */
844 ex ex::content(const symbol &x) const
848 if (is_exactly_a<numeric>(*this))
849 return info(info_flags::negative) ? -*this : *this;
854 // First, try the integer content
855 ex c = e.integer_content();
857 ex lcoeff = r.lcoeff(x);
858 if (lcoeff.info(info_flags::integer))
861 // GCD of all coefficients
862 int deg = e.degree(x);
863 int ldeg = e.ldegree(x);
865 return e.lcoeff(x) / e.unit(x);
867 for (int i=ldeg; i<=deg; i++)
868 c = gcd(e.coeff(x, i), c, NULL, NULL, false);
873 /** Compute primitive part of a multivariate polynomial in Z[x].
874 * The product of unit part, content part, and primitive part is the
877 * @param x variable in which to compute the primitive part
878 * @return primitive part
879 * @see ex::unit, ex::content */
880 ex ex::primpart(const symbol &x) const
884 if (is_exactly_a<numeric>(*this))
891 if (is_exactly_a<numeric>(c))
892 return *this / (c * u);
894 return quo(*this, c * u, x, false);
898 /** Compute primitive part of a multivariate polynomial in Z[x] when the
899 * content part is already known. This function is faster in computing the
900 * primitive part than the previous function.
902 * @param x variable in which to compute the primitive part
903 * @param c previously computed content part
904 * @return primitive part */
905 ex ex::primpart(const symbol &x, const ex &c) const
911 if (is_exactly_a<numeric>(*this))
915 if (is_exactly_a<numeric>(c))
916 return *this / (c * u);
918 return quo(*this, c * u, x, false);
923 * GCD of multivariate polynomials
926 /** Compute GCD of multivariate polynomials using the subresultant PRS
927 * algorithm. This function is used internally by gcd().
929 * @param a first multivariate polynomial
930 * @param b second multivariate polynomial
931 * @param var iterator to first element of vector of sym_desc structs
932 * @return the GCD as a new expression
935 static ex sr_gcd(const ex &a, const ex &b, sym_desc_vec::const_iterator var)
941 // The first symbol is our main variable
942 const symbol &x = *(var->sym);
944 // Sort c and d so that c has higher degree
946 int adeg = a.degree(x), bdeg = b.degree(x);
960 // Remove content from c and d, to be attached to GCD later
961 ex cont_c = c.content(x);
962 ex cont_d = d.content(x);
963 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
966 c = c.primpart(x, cont_c);
967 d = d.primpart(x, cont_d);
969 // First element of subresultant sequence
970 ex r = _ex0, ri = _ex1, psi = _ex1;
971 int delta = cdeg - ddeg;
975 // Calculate polynomial pseudo-remainder
976 r = prem(c, d, x, false);
978 return gamma * d.primpart(x);
982 if (!divide_in_z(r, ri * pow(psi, delta), d, var))
983 throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
986 if (is_exactly_a<numeric>(r))
989 return gamma * r.primpart(x);
992 // Next element of subresultant sequence
993 ri = c.expand().lcoeff(x);
997 divide_in_z(pow(ri, delta), pow(psi, delta-1), psi, var+1);
1003 /** Return maximum (absolute value) coefficient of a polynomial.
1004 * This function is used internally by heur_gcd().
1006 * @param e expanded multivariate polynomial
1007 * @return maximum coefficient
1009 numeric ex::max_coefficient() const
1011 return bp->max_coefficient();
1014 /** Implementation ex::max_coefficient().
1016 numeric basic::max_coefficient() const
1021 numeric numeric::max_coefficient() const
1026 numeric add::max_coefficient() const
1028 epvector::const_iterator it = seq.begin();
1029 epvector::const_iterator itend = seq.end();
1030 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1031 numeric cur_max = abs(ex_to<numeric>(overall_coeff));
1032 while (it != itend) {
1034 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
1035 a = abs(ex_to<numeric>(it->coeff));
1043 numeric mul::max_coefficient() const
1045 #ifdef DO_GINAC_ASSERT
1046 epvector::const_iterator it = seq.begin();
1047 epvector::const_iterator itend = seq.end();
1048 while (it != itend) {
1049 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
1052 #endif // def DO_GINAC_ASSERT
1053 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1054 return abs(ex_to<numeric>(overall_coeff));
1058 /** Apply symmetric modular homomorphism to an expanded multivariate
1059 * polynomial. This function is usually used internally by heur_gcd().
1062 * @return mapped polynomial
1064 ex basic::smod(const numeric &xi) const
1069 ex numeric::smod(const numeric &xi) const
1071 return GiNaC::smod(*this, xi);
1074 ex add::smod(const numeric &xi) const
1077 newseq.reserve(seq.size()+1);
1078 epvector::const_iterator it = seq.begin();
1079 epvector::const_iterator itend = seq.end();
1080 while (it != itend) {
1081 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
1082 numeric coeff = GiNaC::smod(ex_to<numeric>(it->coeff), xi);
1083 if (!coeff.is_zero())
1084 newseq.push_back(expair(it->rest, coeff));
1087 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1088 numeric coeff = GiNaC::smod(ex_to<numeric>(overall_coeff), xi);
1089 return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
1092 ex mul::smod(const numeric &xi) const
1094 #ifdef DO_GINAC_ASSERT
1095 epvector::const_iterator it = seq.begin();
1096 epvector::const_iterator itend = seq.end();
1097 while (it != itend) {
1098 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
1101 #endif // def DO_GINAC_ASSERT
1102 mul * mulcopyp = new mul(*this);
1103 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1104 mulcopyp->overall_coeff = GiNaC::smod(ex_to<numeric>(overall_coeff),xi);
1105 mulcopyp->clearflag(status_flags::evaluated);
1106 mulcopyp->clearflag(status_flags::hash_calculated);
1107 return mulcopyp->setflag(status_flags::dynallocated);
1111 /** xi-adic polynomial interpolation */
1112 static ex interpolate(const ex &gamma, const numeric &xi, const symbol &x, int degree_hint = 1)
1114 exvector g; g.reserve(degree_hint);
1116 numeric rxi = xi.inverse();
1117 for (int i=0; !e.is_zero(); i++) {
1119 g.push_back(gi * power(x, i));
1122 return (new add(g))->setflag(status_flags::dynallocated);
1125 /** Exception thrown by heur_gcd() to signal failure. */
1126 class gcdheu_failed {};
1128 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1129 * get_symbol_stats() must have been called previously with the input
1130 * polynomials and an iterator to the first element of the sym_desc vector
1131 * passed in. This function is used internally by gcd().
1133 * @param a first multivariate polynomial (expanded)
1134 * @param b second multivariate polynomial (expanded)
1135 * @param ca cofactor of polynomial a (returned), NULL to suppress
1136 * calculation of cofactor
1137 * @param cb cofactor of polynomial b (returned), NULL to suppress
1138 * calculation of cofactor
1139 * @param var iterator to first element of vector of sym_desc structs
1140 * @return the GCD as a new expression
1142 * @exception gcdheu_failed() */
1143 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
1149 // Algorithm only works for non-vanishing input polynomials
1150 if (a.is_zero() || b.is_zero())
1151 return (new fail())->setflag(status_flags::dynallocated);
1153 // GCD of two numeric values -> CLN
1154 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b)) {
1155 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1157 *ca = ex_to<numeric>(a) / g;
1159 *cb = ex_to<numeric>(b) / g;
1163 // The first symbol is our main variable
1164 const symbol &x = *(var->sym);
1166 // Remove integer content
1167 numeric gc = gcd(a.integer_content(), b.integer_content());
1168 numeric rgc = gc.inverse();
1171 int maxdeg = std::max(p.degree(x), q.degree(x));
1173 // Find evaluation point
1174 numeric mp = p.max_coefficient();
1175 numeric mq = q.max_coefficient();
1178 xi = mq * _num2 + _num2;
1180 xi = mp * _num2 + _num2;
1183 for (int t=0; t<6; t++) {
1184 if (xi.int_length() * maxdeg > 100000) {
1185 throw gcdheu_failed();
1188 // Apply evaluation homomorphism and calculate GCD
1190 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();
1191 if (!is_exactly_a<fail>(gamma)) {
1193 // Reconstruct polynomial from GCD of mapped polynomials
1194 ex g = interpolate(gamma, xi, x, maxdeg);
1196 // Remove integer content
1197 g /= g.integer_content();
1199 // If the calculated polynomial divides both p and q, this is the GCD
1201 if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1203 ex lc = g.lcoeff(x);
1204 if (is_exactly_a<numeric>(lc) && ex_to<numeric>(lc).is_negative())
1211 // Next evaluation point
1212 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1214 return (new fail())->setflag(status_flags::dynallocated);
1218 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1221 * @param a first multivariate polynomial
1222 * @param b second multivariate polynomial
1223 * @param check_args check whether a and b are polynomials with rational
1224 * coefficients (defaults to "true")
1225 * @return the GCD as a new expression */
1226 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1232 // GCD of numerics -> CLN
1233 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b)) {
1234 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1243 *ca = ex_to<numeric>(a) / g;
1245 *cb = ex_to<numeric>(b) / g;
1252 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))) {
1253 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1256 // Partially factored cases (to avoid expanding large expressions)
1257 if (is_exactly_a<mul>(a)) {
1258 if (is_exactly_a<mul>(b) && b.nops() > a.nops())
1261 size_t num = a.nops();
1262 exvector g; g.reserve(num);
1263 exvector acc_ca; acc_ca.reserve(num);
1265 for (size_t i=0; i<num; i++) {
1266 ex part_ca, part_cb;
1267 g.push_back(gcd(a.op(i), part_b, &part_ca, &part_cb, check_args));
1268 acc_ca.push_back(part_ca);
1272 *ca = (new mul(acc_ca))->setflag(status_flags::dynallocated);
1275 return (new mul(g))->setflag(status_flags::dynallocated);
1276 } else if (is_exactly_a<mul>(b)) {
1277 if (is_exactly_a<mul>(a) && a.nops() > b.nops())
1280 size_t num = b.nops();
1281 exvector g; g.reserve(num);
1282 exvector acc_cb; acc_cb.reserve(num);
1284 for (size_t i=0; i<num; i++) {
1285 ex part_ca, part_cb;
1286 g.push_back(gcd(part_a, b.op(i), &part_ca, &part_cb, check_args));
1287 acc_cb.push_back(part_cb);
1293 *cb = (new mul(acc_cb))->setflag(status_flags::dynallocated);
1294 return (new mul(g))->setflag(status_flags::dynallocated);
1298 // Input polynomials of the form poly^n are sometimes also trivial
1299 if (is_exactly_a<power>(a)) {
1301 if (is_exactly_a<power>(b)) {
1302 if (p.is_equal(b.op(0))) {
1303 // a = p^n, b = p^m, gcd = p^min(n, m)
1304 ex exp_a = a.op(1), exp_b = b.op(1);
1305 if (exp_a < exp_b) {
1309 *cb = power(p, exp_b - exp_a);
1310 return power(p, exp_a);
1313 *ca = power(p, exp_a - exp_b);
1316 return power(p, exp_b);
1320 if (p.is_equal(b)) {
1321 // a = p^n, b = p, gcd = p
1323 *ca = power(p, a.op(1) - 1);
1329 } else if (is_exactly_a<power>(b)) {
1331 if (p.is_equal(a)) {
1332 // a = p, b = p^n, gcd = p
1336 *cb = power(p, b.op(1) - 1);
1342 // Some trivial cases
1343 ex aex = a.expand(), bex = b.expand();
1344 if (aex.is_zero()) {
1351 if (bex.is_zero()) {
1358 if (aex.is_equal(_ex1) || bex.is_equal(_ex1)) {
1366 if (a.is_equal(b)) {
1375 // Gather symbol statistics
1376 sym_desc_vec sym_stats;
1377 get_symbol_stats(a, b, sym_stats);
1379 // The symbol with least degree is our main variable
1380 sym_desc_vec::const_iterator var = sym_stats.begin();
1381 const symbol &x = *(var->sym);
1383 // Cancel trivial common factor
1384 int ldeg_a = var->ldeg_a;
1385 int ldeg_b = var->ldeg_b;
1386 int min_ldeg = std::min(ldeg_a,ldeg_b);
1388 ex common = power(x, min_ldeg);
1389 return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1392 // Try to eliminate variables
1393 if (var->deg_a == 0) {
1394 ex c = bex.content(x);
1395 ex g = gcd(aex, c, ca, cb, false);
1397 *cb *= bex.unit(x) * bex.primpart(x, c);
1399 } else if (var->deg_b == 0) {
1400 ex c = aex.content(x);
1401 ex g = gcd(c, bex, ca, cb, false);
1403 *ca *= aex.unit(x) * aex.primpart(x, c);
1407 // Try heuristic algorithm first, fall back to PRS if that failed
1410 g = heur_gcd(aex, bex, ca, cb, var);
1411 } catch (gcdheu_failed) {
1414 if (is_exactly_a<fail>(g)) {
1418 g = sr_gcd(aex, bex, var);
1419 if (g.is_equal(_ex1)) {
1420 // Keep cofactors factored if possible
1427 divide(aex, g, *ca, false);
1429 divide(bex, g, *cb, false);
1432 if (g.is_equal(_ex1)) {
1433 // Keep cofactors factored if possible
1445 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1447 * @param a first multivariate polynomial
1448 * @param b second multivariate polynomial
1449 * @param check_args check whether a and b are polynomials with rational
1450 * coefficients (defaults to "true")
1451 * @return the LCM as a new expression */
1452 ex lcm(const ex &a, const ex &b, bool check_args)
1454 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b))
1455 return lcm(ex_to<numeric>(a), ex_to<numeric>(b));
1456 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
1457 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1460 ex g = gcd(a, b, &ca, &cb, false);
1466 * Square-free factorization
1469 /** Compute square-free factorization of multivariate polynomial a(x) using
1470 * YunĀ“s algorithm. Used internally by sqrfree().
1472 * @param a multivariate polynomial over Z[X], treated here as univariate
1474 * @param x variable to factor in
1475 * @return vector of factors sorted in ascending degree */
1476 static exvector sqrfree_yun(const ex &a, const symbol &x)
1482 if (g.is_equal(_ex1)) {
1493 } while (!z.is_zero());
1498 /** Compute a square-free factorization of a multivariate polynomial in Q[X].
1500 * @param a multivariate polynomial over Q[X]
1501 * @param x lst of variables to factor in, may be left empty for autodetection
1502 * @return a square-free factorization of \p a.
1505 * A polynomial \f$p(X) \in C[X]\f$ is said <EM>square-free</EM>
1506 * if, whenever any two polynomials \f$q(X)\f$ and \f$r(X)\f$
1509 * p(X) = q(X)^2 r(X),
1511 * we have \f$q(X) \in C\f$.
1512 * This means that \f$p(X)\f$ has no repeated factors, apart
1513 * eventually from constants.
1514 * Given a polynomial \f$p(X) \in C[X]\f$, we say that the
1517 * p(X) = b \cdot p_1(X)^{a_1} \cdot p_2(X)^{a_2} \cdots p_r(X)^{a_r}
1519 * is a <EM>square-free factorization</EM> of \f$p(X)\f$ if the
1520 * following conditions hold:
1521 * -# \f$b \in C\f$ and \f$b \neq 0\f$;
1522 * -# \f$a_i\f$ is a positive integer for \f$i = 1, \ldots, r\f$;
1523 * -# the degree of the polynomial \f$p_i\f$ is strictly positive
1524 * for \f$i = 1, \ldots, r\f$;
1525 * -# the polynomial \f$\Pi_{i=1}^r p_i(X)\f$ is square-free.
1527 * Square-free factorizations need not be unique. For example, if
1528 * \f$a_i\f$ is even, we could change the polynomial \f$p_i(X)\f$
1529 * into \f$-p_i(X)\f$.
1530 * Observe also that the factors \f$p_i(X)\f$ need not be irreducible
1533 ex sqrfree(const ex &a, const lst &l)
1535 if (is_exactly_a<numeric>(a) || // algorithm does not trap a==0
1536 is_a<symbol>(a)) // shortcut
1539 // If no lst of variables to factorize in was specified we have to
1540 // invent one now. Maybe one can optimize here by reversing the order
1541 // or so, I don't know.
1545 get_symbol_stats(a, _ex0, sdv);
1546 sym_desc_vec::const_iterator it = sdv.begin(), itend = sdv.end();
1547 while (it != itend) {
1548 args.append(*it->sym);
1555 // Find the symbol to factor in at this stage
1556 if (!is_a<symbol>(args.op(0)))
1557 throw (std::runtime_error("sqrfree(): invalid factorization variable"));
1558 const symbol &x = ex_to<symbol>(args.op(0));
1560 // convert the argument from something in Q[X] to something in Z[X]
1561 const numeric lcm = lcm_of_coefficients_denominators(a);
1562 const ex tmp = multiply_lcm(a,lcm);
1565 exvector factors = sqrfree_yun(tmp,x);
1567 // construct the next list of symbols with the first element popped
1569 newargs.remove_first();
1571 // recurse down the factors in remaining variables
1572 if (newargs.nops()>0) {
1573 exvector::iterator i = factors.begin();
1574 while (i != factors.end()) {
1575 *i = sqrfree(*i, newargs);
1580 // Done with recursion, now construct the final result
1582 exvector::const_iterator it = factors.begin(), itend = factors.end();
1583 for (int p = 1; it!=itend; ++it, ++p)
1584 result *= power(*it, p);
1586 // Yun's algorithm does not account for constant factors. (For univariate
1587 // polynomials it works only in the monic case.) We can correct this by
1588 // inserting what has been lost back into the result. For completeness
1589 // we'll also have to recurse down that factor in the remaining variables.
1590 if (newargs.nops()>0)
1591 result *= sqrfree(quo(tmp, result, x), newargs);
1593 result *= quo(tmp, result, x);
1595 // Put in the reational overall factor again and return
1596 return result * lcm.inverse();
1600 /** Compute square-free partial fraction decomposition of rational function
1603 * @param a rational function over Z[x], treated as univariate polynomial
1605 * @param x variable to factor in
1606 * @return decomposed rational function */
1607 ex sqrfree_parfrac(const ex & a, const symbol & x)
1609 // Find numerator and denominator
1610 ex nd = numer_denom(a);
1611 ex numer = nd.op(0), denom = nd.op(1);
1612 //clog << "numer = " << numer << ", denom = " << denom << endl;
1614 // Convert N(x)/D(x) -> Q(x) + R(x)/D(x), so degree(R) < degree(D)
1615 ex red_poly = quo(numer, denom, x), red_numer = rem(numer, denom, x).expand();
1616 //clog << "red_poly = " << red_poly << ", red_numer = " << red_numer << endl;
1618 // Factorize denominator and compute cofactors
1619 exvector yun = sqrfree_yun(denom, x);
1620 //clog << "yun factors: " << exprseq(yun) << endl;
1621 size_t num_yun = yun.size();
1622 exvector factor; factor.reserve(num_yun);
1623 exvector cofac; cofac.reserve(num_yun);
1624 for (size_t i=0; i<num_yun; i++) {
1625 if (!yun[i].is_equal(_ex1)) {
1626 for (size_t j=0; j<=i; j++) {
1627 factor.push_back(pow(yun[i], j+1));
1629 for (size_t k=0; k<num_yun; k++) {
1631 prod *= pow(yun[k], i-j);
1633 prod *= pow(yun[k], k+1);
1635 cofac.push_back(prod.expand());
1639 size_t num_factors = factor.size();
1640 //clog << "factors : " << exprseq(factor) << endl;
1641 //clog << "cofactors: " << exprseq(cofac) << endl;
1643 // Construct coefficient matrix for decomposition
1644 int max_denom_deg = denom.degree(x);
1645 matrix sys(max_denom_deg + 1, num_factors);
1646 matrix rhs(max_denom_deg + 1, 1);
1647 for (int i=0; i<=max_denom_deg; i++) {
1648 for (size_t j=0; j<num_factors; j++)
1649 sys(i, j) = cofac[j].coeff(x, i);
1650 rhs(i, 0) = red_numer.coeff(x, i);
1652 //clog << "coeffs: " << sys << endl;
1653 //clog << "rhs : " << rhs << endl;
1655 // Solve resulting linear system
1656 matrix vars(num_factors, 1);
1657 for (size_t i=0; i<num_factors; i++)
1658 vars(i, 0) = symbol();
1659 matrix sol = sys.solve(vars, rhs);
1661 // Sum up decomposed fractions
1663 for (size_t i=0; i<num_factors; i++)
1664 sum += sol(i, 0) / factor[i];
1666 return red_poly + sum;
1671 * Normal form of rational functions
1675 * Note: The internal normal() functions (= basic::normal() and overloaded
1676 * functions) all return lists of the form {numerator, denominator}. This
1677 * is to get around mul::eval()'s automatic expansion of numeric coefficients.
1678 * E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
1679 * the information that (a+b) is the numerator and 3 is the denominator.
1683 /** Create a symbol for replacing the expression "e" (or return a previously
1684 * assigned symbol). The symbol and expression are appended to repl, for
1685 * a later application of subs().
1686 * @see ex::normal */
1687 static ex replace_with_symbol(const ex & e, exmap & repl)
1689 // Expression already in repl? Then return the assigned symbol
1690 for (exmap::const_iterator it = repl.begin(); it != repl.end(); ++it)
1691 if (it->second.is_equal(e))
1694 // Otherwise create new symbol and add to list, taking care that the
1695 // replacement expression doesn't itself contain symbols from repl,
1696 // because subs() is not recursive
1697 ex es = (new symbol)->setflag(status_flags::dynallocated);
1698 ex e_replaced = e.subs(repl, subs_options::no_pattern);
1699 repl[es] = e_replaced;
1703 /** Create a symbol for replacing the expression "e" (or return a previously
1704 * assigned symbol). An expression of the form "symbol == expression" is added
1705 * to repl_lst and the symbol is returned.
1706 * @see basic::to_rational
1707 * @see basic::to_polynomial */
1708 static ex replace_with_symbol(const ex & e, lst & repl_lst)
1710 // Expression already in repl_lst? Then return the assigned symbol
1711 for (lst::const_iterator it = repl_lst.begin(); it != repl_lst.end(); ++it)
1712 if (it->op(1).is_equal(e))
1715 // Otherwise create new symbol and add to list, taking care that the
1716 // replacement expression doesn't itself contain symbols from the repl_lst,
1717 // because subs() is not recursive
1718 ex es = (new symbol)->setflag(status_flags::dynallocated);
1719 ex e_replaced = e.subs(repl_lst, subs_options::no_pattern);
1720 repl_lst.append(es == e_replaced);
1725 /** Function object to be applied by basic::normal(). */
1726 struct normal_map_function : public map_function {
1728 normal_map_function(int l) : level(l) {}
1729 ex operator()(const ex & e) { return normal(e, level); }
1732 /** Default implementation of ex::normal(). It normalizes the children and
1733 * replaces the object with a temporary symbol.
1734 * @see ex::normal */
1735 ex basic::normal(exmap & repl, int level) const
1738 return (new lst(replace_with_symbol(*this, repl), _ex1))->setflag(status_flags::dynallocated);
1741 return (new lst(replace_with_symbol(*this, repl), _ex1))->setflag(status_flags::dynallocated);
1742 else if (level == -max_recursion_level)
1743 throw(std::runtime_error("max recursion level reached"));
1745 normal_map_function map_normal(level - 1);
1746 return (new lst(replace_with_symbol(map(map_normal), repl), _ex1))->setflag(status_flags::dynallocated);
1752 /** Implementation of ex::normal() for symbols. This returns the unmodified symbol.
1753 * @see ex::normal */
1754 ex symbol::normal(exmap & repl, int level) const
1756 return (new lst(*this, _ex1))->setflag(status_flags::dynallocated);
1760 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1761 * into re+I*im and replaces I and non-rational real numbers with a temporary
1763 * @see ex::normal */
1764 ex numeric::normal(exmap & repl, int level) const
1766 numeric num = numer();
1769 if (num.is_real()) {
1770 if (!num.is_integer())
1771 numex = replace_with_symbol(numex, repl);
1773 numeric re = num.real(), im = num.imag();
1774 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl);
1775 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl);
1776 numex = re_ex + im_ex * replace_with_symbol(I, repl);
1779 // Denominator is always a real integer (see numeric::denom())
1780 return (new lst(numex, denom()))->setflag(status_flags::dynallocated);
1784 /** Fraction cancellation.
1785 * @param n numerator
1786 * @param d denominator
1787 * @return cancelled fraction {n, d} as a list */
1788 static ex frac_cancel(const ex &n, const ex &d)
1792 numeric pre_factor = _num1;
1794 //std::clog << "frac_cancel num = " << num << ", den = " << den << std::endl;
1796 // Handle trivial case where denominator is 1
1797 if (den.is_equal(_ex1))
1798 return (new lst(num, den))->setflag(status_flags::dynallocated);
1800 // Handle special cases where numerator or denominator is 0
1802 return (new lst(num, _ex1))->setflag(status_flags::dynallocated);
1803 if (den.expand().is_zero())
1804 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
1806 // Bring numerator and denominator to Z[X] by multiplying with
1807 // LCM of all coefficients' denominators
1808 numeric num_lcm = lcm_of_coefficients_denominators(num);
1809 numeric den_lcm = lcm_of_coefficients_denominators(den);
1810 num = multiply_lcm(num, num_lcm);
1811 den = multiply_lcm(den, den_lcm);
1812 pre_factor = den_lcm / num_lcm;
1814 // Cancel GCD from numerator and denominator
1816 if (gcd(num, den, &cnum, &cden, false) != _ex1) {
1821 // Make denominator unit normal (i.e. coefficient of first symbol
1822 // as defined by get_first_symbol() is made positive)
1823 if (is_exactly_a<numeric>(den)) {
1824 if (ex_to<numeric>(den).is_negative()) {
1830 if (get_first_symbol(den, x)) {
1831 GINAC_ASSERT(is_exactly_a<numeric>(den.unit(*x)));
1832 if (ex_to<numeric>(den.unit(*x)).is_negative()) {
1839 // Return result as list
1840 //std::clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << std::endl;
1841 return (new lst(num * pre_factor.numer(), den * pre_factor.denom()))->setflag(status_flags::dynallocated);
1845 /** Implementation of ex::normal() for a sum. It expands terms and performs
1846 * fractional addition.
1847 * @see ex::normal */
1848 ex add::normal(exmap & repl, int level) const
1851 return (new lst(replace_with_symbol(*this, repl), _ex1))->setflag(status_flags::dynallocated);
1852 else if (level == -max_recursion_level)
1853 throw(std::runtime_error("max recursion level reached"));
1855 // Normalize children and split each one into numerator and denominator
1856 exvector nums, dens;
1857 nums.reserve(seq.size()+1);
1858 dens.reserve(seq.size()+1);
1859 epvector::const_iterator it = seq.begin(), itend = seq.end();
1860 while (it != itend) {
1861 ex n = ex_to<basic>(recombine_pair_to_ex(*it)).normal(repl, level-1);
1862 nums.push_back(n.op(0));
1863 dens.push_back(n.op(1));
1866 ex n = ex_to<numeric>(overall_coeff).normal(repl, level-1);
1867 nums.push_back(n.op(0));
1868 dens.push_back(n.op(1));
1869 GINAC_ASSERT(nums.size() == dens.size());
1871 // Now, nums is a vector of all numerators and dens is a vector of
1873 //std::clog << "add::normal uses " << nums.size() << " summands:\n";
1875 // Add fractions sequentially
1876 exvector::const_iterator num_it = nums.begin(), num_itend = nums.end();
1877 exvector::const_iterator den_it = dens.begin(), den_itend = dens.end();
1878 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
1879 ex num = *num_it++, den = *den_it++;
1880 while (num_it != num_itend) {
1881 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
1882 ex next_num = *num_it++, next_den = *den_it++;
1884 // Trivially add sequences of fractions with identical denominators
1885 while ((den_it != den_itend) && next_den.is_equal(*den_it)) {
1886 next_num += *num_it;
1890 // Additiion of two fractions, taking advantage of the fact that
1891 // the heuristic GCD algorithm computes the cofactors at no extra cost
1892 ex co_den1, co_den2;
1893 ex g = gcd(den, next_den, &co_den1, &co_den2, false);
1894 num = ((num * co_den2) + (next_num * co_den1)).expand();
1895 den *= co_den2; // this is the lcm(den, next_den)
1897 //std::clog << " common denominator = " << den << std::endl;
1899 // Cancel common factors from num/den
1900 return frac_cancel(num, den);
1904 /** Implementation of ex::normal() for a product. It cancels common factors
1906 * @see ex::normal() */
1907 ex mul::normal(exmap & repl, int level) const
1910 return (new lst(replace_with_symbol(*this, repl), _ex1))->setflag(status_flags::dynallocated);
1911 else if (level == -max_recursion_level)
1912 throw(std::runtime_error("max recursion level reached"));
1914 // Normalize children, separate into numerator and denominator
1915 exvector num; num.reserve(seq.size());
1916 exvector den; den.reserve(seq.size());
1918 epvector::const_iterator it = seq.begin(), itend = seq.end();
1919 while (it != itend) {
1920 n = ex_to<basic>(recombine_pair_to_ex(*it)).normal(repl, level-1);
1921 num.push_back(n.op(0));
1922 den.push_back(n.op(1));
1925 n = ex_to<numeric>(overall_coeff).normal(repl, level-1);
1926 num.push_back(n.op(0));
1927 den.push_back(n.op(1));
1929 // Perform fraction cancellation
1930 return frac_cancel((new mul(num))->setflag(status_flags::dynallocated),
1931 (new mul(den))->setflag(status_flags::dynallocated));
1935 /** Implementation of ex::normal() for powers. It normalizes the basis,
1936 * distributes integer exponents to numerator and denominator, and replaces
1937 * non-integer powers by temporary symbols.
1938 * @see ex::normal */
1939 ex power::normal(exmap & repl, int level) const
1942 return (new lst(replace_with_symbol(*this, repl), _ex1))->setflag(status_flags::dynallocated);
1943 else if (level == -max_recursion_level)
1944 throw(std::runtime_error("max recursion level reached"));
1946 // Normalize basis and exponent (exponent gets reassembled)
1947 ex n_basis = ex_to<basic>(basis).normal(repl, level-1);
1948 ex n_exponent = ex_to<basic>(exponent).normal(repl, level-1);
1949 n_exponent = n_exponent.op(0) / n_exponent.op(1);
1951 if (n_exponent.info(info_flags::integer)) {
1953 if (n_exponent.info(info_flags::positive)) {
1955 // (a/b)^n -> {a^n, b^n}
1956 return (new lst(power(n_basis.op(0), n_exponent), power(n_basis.op(1), n_exponent)))->setflag(status_flags::dynallocated);
1958 } else if (n_exponent.info(info_flags::negative)) {
1960 // (a/b)^-n -> {b^n, a^n}
1961 return (new lst(power(n_basis.op(1), -n_exponent), power(n_basis.op(0), -n_exponent)))->setflag(status_flags::dynallocated);
1966 if (n_exponent.info(info_flags::positive)) {
1968 // (a/b)^x -> {sym((a/b)^x), 1}
1969 return (new lst(replace_with_symbol(power(n_basis.op(0) / n_basis.op(1), n_exponent), repl), _ex1))->setflag(status_flags::dynallocated);
1971 } else if (n_exponent.info(info_flags::negative)) {
1973 if (n_basis.op(1).is_equal(_ex1)) {
1975 // a^-x -> {1, sym(a^x)}
1976 return (new lst(_ex1, replace_with_symbol(power(n_basis.op(0), -n_exponent), repl)))->setflag(status_flags::dynallocated);
1980 // (a/b)^-x -> {sym((b/a)^x), 1}
1981 return (new lst(replace_with_symbol(power(n_basis.op(1) / n_basis.op(0), -n_exponent), repl), _ex1))->setflag(status_flags::dynallocated);
1986 // (a/b)^x -> {sym((a/b)^x, 1}
1987 return (new lst(replace_with_symbol(power(n_basis.op(0) / n_basis.op(1), n_exponent), repl), _ex1))->setflag(status_flags::dynallocated);
1991 /** Implementation of ex::normal() for pseries. It normalizes each coefficient
1992 * and replaces the series by a temporary symbol.
1993 * @see ex::normal */
1994 ex pseries::normal(exmap & repl, int level) const
1997 epvector::const_iterator i = seq.begin(), end = seq.end();
1999 ex restexp = i->rest.normal();
2000 if (!restexp.is_zero())
2001 newseq.push_back(expair(restexp, i->coeff));
2004 ex n = pseries(relational(var,point), newseq);
2005 return (new lst(replace_with_symbol(n, repl), _ex1))->setflag(status_flags::dynallocated);
2009 /** Normalization of rational functions.
2010 * This function converts an expression to its normal form
2011 * "numerator/denominator", where numerator and denominator are (relatively
2012 * prime) polynomials. Any subexpressions which are not rational functions
2013 * (like non-rational numbers, non-integer powers or functions like sin(),
2014 * cos() etc.) are replaced by temporary symbols which are re-substituted by
2015 * the (normalized) subexpressions before normal() returns (this way, any
2016 * expression can be treated as a rational function). normal() is applied
2017 * recursively to arguments of functions etc.
2019 * @param level maximum depth of recursion
2020 * @return normalized expression */
2021 ex ex::normal(int level) const
2025 ex e = bp->normal(repl, level);
2026 GINAC_ASSERT(is_a<lst>(e));
2028 // Re-insert replaced symbols
2030 e = e.subs(repl, subs_options::no_pattern);
2032 // Convert {numerator, denominator} form back to fraction
2033 return e.op(0) / e.op(1);
2036 /** Get numerator of an expression. If the expression is not of the normal
2037 * form "numerator/denominator", it is first converted to this form and
2038 * then the numerator is returned.
2041 * @return numerator */
2042 ex ex::numer() const
2046 ex e = bp->normal(repl, 0);
2047 GINAC_ASSERT(is_a<lst>(e));
2049 // Re-insert replaced symbols
2053 return e.op(0).subs(repl, subs_options::no_pattern);
2056 /** Get denominator of an expression. If the expression is not of the normal
2057 * form "numerator/denominator", it is first converted to this form and
2058 * then the denominator is returned.
2061 * @return denominator */
2062 ex ex::denom() const
2066 ex e = bp->normal(repl, 0);
2067 GINAC_ASSERT(is_a<lst>(e));
2069 // Re-insert replaced symbols
2073 return e.op(1).subs(repl, subs_options::no_pattern);
2076 /** Get numerator and denominator of an expression. If the expresison is not
2077 * of the normal form "numerator/denominator", it is first converted to this
2078 * form and then a list [numerator, denominator] is returned.
2081 * @return a list [numerator, denominator] */
2082 ex ex::numer_denom() const
2086 ex e = bp->normal(repl, 0);
2087 GINAC_ASSERT(is_a<lst>(e));
2089 // Re-insert replaced symbols
2093 return e.subs(repl, subs_options::no_pattern);
2097 /** Rationalization of non-rational functions.
2098 * This function converts a general expression to a rational function
2099 * by replacing all non-rational subexpressions (like non-rational numbers,
2100 * non-integer powers or functions like sin(), cos() etc.) to temporary
2101 * symbols. This makes it possible to use functions like gcd() and divide()
2102 * on non-rational functions by applying to_rational() on the arguments,
2103 * calling the desired function and re-substituting the temporary symbols
2104 * in the result. To make the last step possible, all temporary symbols and
2105 * their associated expressions are collected in the list specified by the
2106 * repl_lst parameter in the form {symbol == expression}, ready to be passed
2107 * as an argument to ex::subs().
2109 * @param repl_lst collects a list of all temporary symbols and their replacements
2110 * @return rationalized expression */
2111 ex ex::to_rational(lst &repl_lst) const
2113 return bp->to_rational(repl_lst);
2116 ex ex::to_polynomial(lst &repl_lst) const
2118 return bp->to_polynomial(repl_lst);
2122 /** Default implementation of ex::to_rational(). This replaces the object with
2123 * a temporary symbol. */
2124 ex basic::to_rational(lst &repl_lst) const
2126 return replace_with_symbol(*this, repl_lst);
2129 ex basic::to_polynomial(lst &repl_lst) const
2131 return replace_with_symbol(*this, repl_lst);
2135 /** Implementation of ex::to_rational() for symbols. This returns the
2136 * unmodified symbol. */
2137 ex symbol::to_rational(lst &repl_lst) const
2142 /** Implementation of ex::to_polynomial() for symbols. This returns the
2143 * unmodified symbol. */
2144 ex symbol::to_polynomial(lst &repl_lst) const
2150 /** Implementation of ex::to_rational() for a numeric. It splits complex
2151 * numbers into re+I*im and replaces I and non-rational real numbers with a
2152 * temporary symbol. */
2153 ex numeric::to_rational(lst &repl_lst) const
2157 return replace_with_symbol(*this, repl_lst);
2159 numeric re = real();
2160 numeric im = imag();
2161 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl_lst);
2162 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl_lst);
2163 return re_ex + im_ex * replace_with_symbol(I, repl_lst);
2168 /** Implementation of ex::to_polynomial() for a numeric. It splits complex
2169 * numbers into re+I*im and replaces I and non-integer real numbers with a
2170 * temporary symbol. */
2171 ex numeric::to_polynomial(lst &repl_lst) const
2175 return replace_with_symbol(*this, repl_lst);
2177 numeric re = real();
2178 numeric im = imag();
2179 ex re_ex = re.is_integer() ? re : replace_with_symbol(re, repl_lst);
2180 ex im_ex = im.is_integer() ? im : replace_with_symbol(im, repl_lst);
2181 return re_ex + im_ex * replace_with_symbol(I, repl_lst);
2187 /** Implementation of ex::to_rational() for powers. It replaces non-integer
2188 * powers by temporary symbols. */
2189 ex power::to_rational(lst &repl_lst) const
2191 if (exponent.info(info_flags::integer))
2192 return power(basis.to_rational(repl_lst), exponent);
2194 return replace_with_symbol(*this, repl_lst);
2197 /** Implementation of ex::to_polynomial() for powers. It replaces non-posint
2198 * powers by temporary symbols. */
2199 ex power::to_polynomial(lst &repl_lst) const
2201 if (exponent.info(info_flags::posint))
2202 return power(basis.to_rational(repl_lst), exponent);
2204 return replace_with_symbol(*this, repl_lst);
2208 /** Implementation of ex::to_rational() for expairseqs. */
2209 ex expairseq::to_rational(lst &repl_lst) const
2212 s.reserve(seq.size());
2213 epvector::const_iterator i = seq.begin(), end = seq.end();
2215 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*i).to_rational(repl_lst)));
2218 ex oc = overall_coeff.to_rational(repl_lst);
2219 if (oc.info(info_flags::numeric))
2220 return thisexpairseq(s, overall_coeff);
2222 s.push_back(combine_ex_with_coeff_to_pair(oc, _ex1));
2223 return thisexpairseq(s, default_overall_coeff());
2226 /** Implementation of ex::to_polynomial() for expairseqs. */
2227 ex expairseq::to_polynomial(lst &repl_lst) const
2230 s.reserve(seq.size());
2231 epvector::const_iterator i = seq.begin(), end = seq.end();
2233 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*i).to_polynomial(repl_lst)));
2236 ex oc = overall_coeff.to_polynomial(repl_lst);
2237 if (oc.info(info_flags::numeric))
2238 return thisexpairseq(s, overall_coeff);
2240 s.push_back(combine_ex_with_coeff_to_pair(oc, _ex1));
2241 return thisexpairseq(s, default_overall_coeff());
2245 /** Remove the common factor in the terms of a sum 'e' by calculating the GCD,
2246 * and multiply it into the expression 'factor' (which needs to be initialized
2247 * to 1, unless you're accumulating factors). */
2248 static ex find_common_factor(const ex & e, ex & factor, lst & repl)
2250 if (is_exactly_a<add>(e)) {
2252 size_t num = e.nops();
2253 exvector terms; terms.reserve(num);
2256 // Find the common GCD
2257 for (size_t i=0; i<num; i++) {
2258 ex x = e.op(i).to_polynomial(repl);
2260 if (is_exactly_a<add>(x) || is_exactly_a<mul>(x)) {
2262 x = find_common_factor(x, f, repl);
2274 if (gc.is_equal(_ex1))
2277 // The GCD is the factor we pull out
2280 // Now divide all terms by the GCD
2281 for (size_t i=0; i<num; i++) {
2284 // Try to avoid divide() because it expands the polynomial
2286 if (is_exactly_a<mul>(t)) {
2287 for (size_t j=0; j<t.nops(); j++) {
2288 if (t.op(j).is_equal(gc)) {
2289 exvector v; v.reserve(t.nops());
2290 for (size_t k=0; k<t.nops(); k++) {
2294 v.push_back(t.op(k));
2296 t = (new mul(v))->setflag(status_flags::dynallocated);
2306 return (new add(terms))->setflag(status_flags::dynallocated);
2308 } else if (is_exactly_a<mul>(e)) {
2310 size_t num = e.nops();
2311 exvector v; v.reserve(num);
2313 for (size_t i=0; i<num; i++)
2314 v.push_back(find_common_factor(e.op(i), factor, repl));
2316 return (new mul(v))->setflag(status_flags::dynallocated);
2318 } else if (is_exactly_a<power>(e)) {
2320 return e.to_polynomial(repl);
2327 /** Collect common factors in sums. This converts expressions like
2328 * 'a*(b*x+b*y)' to 'a*b*(x+y)'. */
2329 ex collect_common_factors(const ex & e)
2331 if (is_exactly_a<add>(e) || is_exactly_a<mul>(e)) {
2335 ex r = find_common_factor(e, factor, repl);
2336 return factor.subs(repl, subs_options::no_pattern) * r.subs(repl, subs_options::no_pattern);
2343 } // namespace GiNaC