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.
10 * GiNaC Copyright (C) 1999-2000 Johannes Gutenberg University Mainz, Germany
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
36 #include "expairseq.h"
45 #include "relational.h"
50 #ifndef NO_GINAC_NAMESPACE
52 #endif // ndef NO_GINAC_NAMESPACE
54 // If comparing expressions (ex::compare()) is fast, you can set this to 1.
55 // Some routines like quo(), rem() and gcd() will then return a quick answer
56 // when they are called with two identical arguments.
57 #define FAST_COMPARE 1
59 // Set this if you want divide_in_z() to use remembering
60 #define USE_REMEMBER 1
63 /** Return pointer to first symbol found in expression. Due to GiNaCĀ“s
64 * internal ordering of terms, it may not be obvious which symbol this
65 * function returns for a given expression.
67 * @param e expression to search
68 * @param x pointer to first symbol found (returned)
69 * @return "false" if no symbol was found, "true" otherwise */
71 static bool get_first_symbol(const ex &e, const symbol *&x)
73 if (is_ex_exactly_of_type(e, symbol)) {
74 x = static_cast<symbol *>(e.bp);
76 } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
77 for (unsigned i=0; i<e.nops(); i++)
78 if (get_first_symbol(e.op(i), x))
80 } else if (is_ex_exactly_of_type(e, power)) {
81 if (get_first_symbol(e.op(0), x))
89 * Statistical information about symbols in polynomials
92 /** This structure holds information about the highest and lowest degrees
93 * in which a symbol appears in two multivariate polynomials "a" and "b".
94 * A vector of these structures with information about all symbols in
95 * two polynomials can be created with the function get_symbol_stats().
97 * @see get_symbol_stats */
99 /** Pointer to symbol */
102 /** Highest degree of symbol in polynomial "a" */
105 /** Highest degree of symbol in polynomial "b" */
108 /** Lowest degree of symbol in polynomial "a" */
111 /** Lowest degree of symbol in polynomial "b" */
114 /** Minimum of ldeg_a and ldeg_b (Used for sorting) */
117 /** Commparison operator for sorting */
118 bool operator<(const sym_desc &x) const {return min_deg < x.min_deg;}
121 // Vector of sym_desc structures
122 typedef vector<sym_desc> sym_desc_vec;
124 // Add symbol the sym_desc_vec (used internally by get_symbol_stats())
125 static void add_symbol(const symbol *s, sym_desc_vec &v)
127 sym_desc_vec::iterator it = v.begin(), itend = v.end();
128 while (it != itend) {
129 if (it->sym->compare(*s) == 0) // If it's already in there, don't add it a second time
138 // Collect all symbols of an expression (used internally by get_symbol_stats())
139 static void collect_symbols(const ex &e, sym_desc_vec &v)
141 if (is_ex_exactly_of_type(e, symbol)) {
142 add_symbol(static_cast<symbol *>(e.bp), v);
143 } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
144 for (unsigned i=0; i<e.nops(); i++)
145 collect_symbols(e.op(i), v);
146 } else if (is_ex_exactly_of_type(e, power)) {
147 collect_symbols(e.op(0), v);
151 /** Collect statistical information about symbols in polynomials.
152 * This function fills in a vector of "sym_desc" structs which contain
153 * information about the highest and lowest degrees of all symbols that
154 * appear in two polynomials. The vector is then sorted by minimum
155 * degree (lowest to highest). The information gathered by this
156 * function is used by the GCD routines to identify trivial factors
157 * and to determine which variable to choose as the main variable
158 * for GCD computation.
160 * @param a first multivariate polynomial
161 * @param b second multivariate polynomial
162 * @param v vector of sym_desc structs (filled in) */
164 static void get_symbol_stats(const ex &a, const ex &b, sym_desc_vec &v)
166 collect_symbols(a.eval(), v); // eval() to expand assigned symbols
167 collect_symbols(b.eval(), v);
168 sym_desc_vec::iterator it = v.begin(), itend = v.end();
169 while (it != itend) {
170 int deg_a = a.degree(*(it->sym));
171 int deg_b = b.degree(*(it->sym));
174 it->min_deg = min(deg_a, deg_b);
175 it->ldeg_a = a.ldegree(*(it->sym));
176 it->ldeg_b = b.ldegree(*(it->sym));
179 sort(v.begin(), v.end());
184 * Computation of LCM of denominators of coefficients of a polynomial
187 // Compute LCM of denominators of coefficients by going through the
188 // expression recursively (used internally by lcm_of_coefficients_denominators())
189 static numeric lcmcoeff(const ex &e, const numeric &l)
191 if (e.info(info_flags::rational))
192 return lcm(ex_to_numeric(e).denom(), l);
193 else if (is_ex_exactly_of_type(e, add)) {
195 for (unsigned i=0; i<e.nops(); i++)
196 c = lcmcoeff(e.op(i), c);
198 } else if (is_ex_exactly_of_type(e, mul)) {
200 for (unsigned i=0; i<e.nops(); i++)
201 c *= lcmcoeff(e.op(i), _num1());
203 } else if (is_ex_exactly_of_type(e, power))
204 return pow(lcmcoeff(e.op(0), l), ex_to_numeric(e.op(1)));
208 /** Compute LCM of denominators of coefficients of a polynomial.
209 * Given a polynomial with rational coefficients, this function computes
210 * the LCM of the denominators of all coefficients. This can be used
211 * to bring a polynomial from Q[X] to Z[X].
213 * @param e multivariate polynomial (need not be expanded)
214 * @return LCM of denominators of coefficients */
216 static numeric lcm_of_coefficients_denominators(const ex &e)
218 return lcmcoeff(e, _num1());
221 /** Bring polynomial from Q[X] to Z[X] by multiplying in the previously
222 * determined LCM of the coefficient's denominators.
224 * @param e multivariate polynomial (need not be expanded)
225 * @param lcm LCM to multiply in */
227 static ex multiply_lcm(const ex &e, const ex &lcm)
229 if (is_ex_exactly_of_type(e, mul)) {
231 for (int i=0; i<e.nops(); i++)
232 c *= multiply_lcm(e.op(i), lcmcoeff(e.op(i), _num1()));
234 } else if (is_ex_exactly_of_type(e, add)) {
236 for (int i=0; i<e.nops(); i++)
237 c += multiply_lcm(e.op(i), lcm);
239 } else if (is_ex_exactly_of_type(e, power)) {
240 return pow(multiply_lcm(e.op(0), pow(lcm, 1/e.op(1))), e.op(1));
246 /** Compute the integer content (= GCD of all numeric coefficients) of an
247 * expanded polynomial.
249 * @param e expanded polynomial
250 * @return integer content */
252 numeric ex::integer_content(void) const
255 return bp->integer_content();
258 numeric basic::integer_content(void) const
263 numeric numeric::integer_content(void) const
268 numeric add::integer_content(void) const
270 epvector::const_iterator it = seq.begin();
271 epvector::const_iterator itend = seq.end();
273 while (it != itend) {
274 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
275 GINAC_ASSERT(is_ex_exactly_of_type(it->coeff,numeric));
276 c = gcd(ex_to_numeric(it->coeff), c);
279 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
280 c = gcd(ex_to_numeric(overall_coeff),c);
284 numeric mul::integer_content(void) const
286 #ifdef DO_GINAC_ASSERT
287 epvector::const_iterator it = seq.begin();
288 epvector::const_iterator itend = seq.end();
289 while (it != itend) {
290 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
293 #endif // def DO_GINAC_ASSERT
294 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
295 return abs(ex_to_numeric(overall_coeff));
300 * Polynomial quotients and remainders
303 /** Quotient q(x) of polynomials a(x) and b(x) in Q[x].
304 * It satisfies a(x)=b(x)*q(x)+r(x).
306 * @param a first polynomial in x (dividend)
307 * @param b second polynomial in x (divisor)
308 * @param x a and b are polynomials in x
309 * @param check_args check whether a and b are polynomials with rational
310 * coefficients (defaults to "true")
311 * @return quotient of a and b in Q[x] */
313 ex quo(const ex &a, const ex &b, const symbol &x, bool check_args)
316 throw(std::overflow_error("quo: division by zero"));
317 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
323 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
324 throw(std::invalid_argument("quo: arguments must be polynomials over the rationals"));
326 // Polynomial long division
331 int bdeg = b.degree(x);
332 int rdeg = r.degree(x);
333 ex blcoeff = b.expand().coeff(x, bdeg);
334 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
335 while (rdeg >= bdeg) {
336 ex term, rcoeff = r.coeff(x, rdeg);
337 if (blcoeff_is_numeric)
338 term = rcoeff / blcoeff;
340 if (!divide(rcoeff, blcoeff, term, false))
341 return *new ex(fail());
343 term *= power(x, rdeg - bdeg);
345 r -= (term * b).expand();
354 /** Remainder r(x) of polynomials a(x) and b(x) in Q[x].
355 * It satisfies a(x)=b(x)*q(x)+r(x).
357 * @param a first polynomial in x (dividend)
358 * @param b second polynomial in x (divisor)
359 * @param x a and b are polynomials in x
360 * @param check_args check whether a and b are polynomials with rational
361 * coefficients (defaults to "true")
362 * @return remainder of a(x) and b(x) in Q[x] */
364 ex rem(const ex &a, const ex &b, const symbol &x, bool check_args)
367 throw(std::overflow_error("rem: division by zero"));
368 if (is_ex_exactly_of_type(a, numeric)) {
369 if (is_ex_exactly_of_type(b, numeric))
378 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
379 throw(std::invalid_argument("rem: arguments must be polynomials over the rationals"));
381 // Polynomial long division
385 int bdeg = b.degree(x);
386 int rdeg = r.degree(x);
387 ex blcoeff = b.expand().coeff(x, bdeg);
388 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
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 ex(fail());
397 term *= power(x, rdeg - bdeg);
398 r -= (term * b).expand();
407 /** Pseudo-remainder of polynomials a(x) and b(x) in Z[x].
409 * @param a first polynomial in x (dividend)
410 * @param b second polynomial in x (divisor)
411 * @param x a and b are polynomials in x
412 * @param check_args check whether a and b are polynomials with rational
413 * coefficients (defaults to "true")
414 * @return pseudo-remainder of a(x) and b(x) in Z[x] */
416 ex prem(const ex &a, const ex &b, const symbol &x, bool check_args)
419 throw(std::overflow_error("prem: division by zero"));
420 if (is_ex_exactly_of_type(a, numeric)) {
421 if (is_ex_exactly_of_type(b, numeric))
426 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
427 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
429 // Polynomial long division
432 int rdeg = r.degree(x);
433 int bdeg = eb.degree(x);
436 blcoeff = eb.coeff(x, bdeg);
440 eb -= blcoeff * power(x, bdeg);
444 int delta = rdeg - bdeg + 1, i = 0;
445 while (rdeg >= bdeg && !r.is_zero()) {
446 ex rlcoeff = r.coeff(x, rdeg);
447 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
451 r -= rlcoeff * power(x, rdeg);
452 r = (blcoeff * r).expand() - term;
456 return power(blcoeff, delta - i) * r;
460 /** Exact polynomial division of a(X) by b(X) in Q[X].
462 * @param a first multivariate polynomial (dividend)
463 * @param b second multivariate polynomial (divisor)
464 * @param q quotient (returned)
465 * @param check_args check whether a and b are polynomials with rational
466 * coefficients (defaults to "true")
467 * @return "true" when exact division succeeds (quotient returned in q),
468 * "false" otherwise */
470 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
474 throw(std::overflow_error("divide: division by zero"));
475 if (is_ex_exactly_of_type(b, numeric)) {
478 } else if (is_ex_exactly_of_type(a, numeric))
486 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
487 throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
491 if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
492 throw(std::invalid_argument("invalid expression in divide()"));
494 // Polynomial long division (recursive)
498 int bdeg = b.degree(*x);
499 int rdeg = r.degree(*x);
500 ex blcoeff = b.expand().coeff(*x, bdeg);
501 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
502 while (rdeg >= bdeg) {
503 ex term, rcoeff = r.coeff(*x, rdeg);
504 if (blcoeff_is_numeric)
505 term = rcoeff / blcoeff;
507 if (!divide(rcoeff, blcoeff, term, false))
509 term *= power(*x, rdeg - bdeg);
511 r -= (term * b).expand();
525 typedef pair<ex, ex> ex2;
526 typedef pair<ex, bool> exbool;
529 bool operator() (const ex2 p, const ex2 q) const
531 return p.first.compare(q.first) < 0 || (!(q.first.compare(p.first) < 0) && p.second.compare(q.second) < 0);
535 typedef map<ex2, exbool, ex2_less> ex2_exbool_remember;
539 /** Exact polynomial division of a(X) by b(X) in Z[X].
540 * This functions works like divide() but the input and output polynomials are
541 * in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
542 * divide(), it doesnĀ“t check whether the input polynomials really are integer
543 * polynomials, so be careful of what you pass in. Also, you have to run
544 * get_symbol_stats() over the input polynomials before calling this function
545 * and pass an iterator to the first element of the sym_desc vector. This
546 * function is used internally by the heur_gcd().
548 * @param a first multivariate polynomial (dividend)
549 * @param b second multivariate polynomial (divisor)
550 * @param q quotient (returned)
551 * @param var iterator to first element of vector of sym_desc structs
552 * @return "true" when exact division succeeds (the quotient is returned in
553 * q), "false" otherwise.
554 * @see get_symbol_stats, heur_gcd */
555 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
559 throw(std::overflow_error("divide_in_z: division by zero"));
560 if (b.is_equal(_ex1())) {
564 if (is_ex_exactly_of_type(a, numeric)) {
565 if (is_ex_exactly_of_type(b, numeric)) {
567 return q.info(info_flags::integer);
580 static ex2_exbool_remember dr_remember;
581 ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
582 if (remembered != dr_remember.end()) {
583 q = remembered->second.first;
584 return remembered->second.second;
589 const symbol *x = var->sym;
592 int adeg = a.degree(*x), bdeg = b.degree(*x);
598 // Polynomial long division (recursive)
604 ex blcoeff = eb.coeff(*x, bdeg);
605 while (rdeg >= bdeg) {
606 ex term, rcoeff = r.coeff(*x, rdeg);
607 if (!divide_in_z(rcoeff, blcoeff, term, var+1))
609 term = (term * power(*x, rdeg - bdeg)).expand();
611 r -= (term * eb).expand();
614 dr_remember[ex2(a, b)] = exbool(q, true);
621 dr_remember[ex2(a, b)] = exbool(q, false);
627 // Trial division using polynomial interpolation
630 // Compute values at evaluation points 0..adeg
631 vector<numeric> alpha; alpha.reserve(adeg + 1);
632 exvector u; u.reserve(adeg + 1);
633 numeric point = _num0();
635 for (i=0; i<=adeg; i++) {
636 ex bs = b.subs(*x == point);
637 while (bs.is_zero()) {
639 bs = b.subs(*x == point);
641 if (!divide_in_z(a.subs(*x == point), bs, c, var+1))
643 alpha.push_back(point);
649 vector<numeric> rcp; rcp.reserve(adeg + 1);
651 for (k=1; k<=adeg; k++) {
652 numeric product = alpha[k] - alpha[0];
654 product *= alpha[k] - alpha[i];
655 rcp.push_back(product.inverse());
658 // Compute Newton coefficients
659 exvector v; v.reserve(adeg + 1);
661 for (k=1; k<=adeg; k++) {
663 for (i=k-2; i>=0; i--)
664 temp = temp * (alpha[k] - alpha[i]) + v[i];
665 v.push_back((u[k] - temp) * rcp[k]);
668 // Convert from Newton form to standard form
670 for (k=adeg-1; k>=0; k--)
671 c = c * (*x - alpha[k]) + v[k];
673 if (c.degree(*x) == (adeg - bdeg)) {
683 * Separation of unit part, content part and primitive part of polynomials
686 /** Compute unit part (= sign of leading coefficient) of a multivariate
687 * polynomial in Z[x]. The product of unit part, content part, and primitive
688 * part is the polynomial itself.
690 * @param x variable in which to compute the unit part
692 * @see ex::content, ex::primpart */
693 ex ex::unit(const symbol &x) const
695 ex c = expand().lcoeff(x);
696 if (is_ex_exactly_of_type(c, numeric))
697 return c < _ex0() ? _ex_1() : _ex1();
700 if (get_first_symbol(c, y))
703 throw(std::invalid_argument("invalid expression in unit()"));
708 /** Compute content part (= unit normal GCD of all coefficients) of a
709 * multivariate polynomial in Z[x]. The product of unit part, content part,
710 * and primitive part is the polynomial itself.
712 * @param x variable in which to compute the content part
713 * @return content part
714 * @see ex::unit, ex::primpart */
715 ex ex::content(const symbol &x) const
719 if (is_ex_exactly_of_type(*this, numeric))
720 return info(info_flags::negative) ? -*this : *this;
725 // First, try the integer content
726 ex c = e.integer_content();
728 ex lcoeff = r.lcoeff(x);
729 if (lcoeff.info(info_flags::integer))
732 // GCD of all coefficients
733 int deg = e.degree(x);
734 int ldeg = e.ldegree(x);
736 return e.lcoeff(x) / e.unit(x);
738 for (int i=ldeg; i<=deg; i++)
739 c = gcd(e.coeff(x, i), c, NULL, NULL, false);
744 /** Compute primitive part of a multivariate polynomial in Z[x].
745 * The product of unit part, content part, and primitive part is the
748 * @param x variable in which to compute the primitive part
749 * @return primitive part
750 * @see ex::unit, ex::content */
751 ex ex::primpart(const symbol &x) const
755 if (is_ex_exactly_of_type(*this, numeric))
762 if (is_ex_exactly_of_type(c, numeric))
763 return *this / (c * u);
765 return quo(*this, c * u, x, false);
769 /** Compute primitive part of a multivariate polynomial in Z[x] when the
770 * content part is already known. This function is faster in computing the
771 * primitive part than the previous function.
773 * @param x variable in which to compute the primitive part
774 * @param c previously computed content part
775 * @return primitive part */
777 ex ex::primpart(const symbol &x, const ex &c) const
783 if (is_ex_exactly_of_type(*this, numeric))
787 if (is_ex_exactly_of_type(c, numeric))
788 return *this / (c * u);
790 return quo(*this, c * u, x, false);
795 * GCD of multivariate polynomials
798 /** Compute GCD of multivariate polynomials using the subresultant PRS
799 * algorithm. This function is used internally gy gcd().
801 * @param a first multivariate polynomial
802 * @param b second multivariate polynomial
803 * @param x pointer to symbol (main variable) in which to compute the GCD in
804 * @return the GCD as a new expression
807 static ex sr_gcd(const ex &a, const ex &b, const symbol *x)
809 // Sort c and d so that c has higher degree
811 int adeg = a.degree(*x), bdeg = b.degree(*x);
825 // Remove content from c and d, to be attached to GCD later
826 ex cont_c = c.content(*x);
827 ex cont_d = d.content(*x);
828 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
831 c = c.primpart(*x, cont_c);
832 d = d.primpart(*x, cont_d);
834 // First element of subresultant sequence
835 ex r = _ex0(), ri = _ex1(), psi = _ex1();
836 int delta = cdeg - ddeg;
839 // Calculate polynomial pseudo-remainder
840 r = prem(c, d, *x, false);
842 return gamma * d.primpart(*x);
845 if (!divide(r, ri * power(psi, delta), d, false))
846 throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
849 if (is_ex_exactly_of_type(r, numeric))
852 return gamma * r.primpart(*x);
855 // Next element of subresultant sequence
856 ri = c.expand().lcoeff(*x);
860 divide(power(ri, delta), power(psi, delta-1), psi, false);
866 /** Return maximum (absolute value) coefficient of a polynomial.
867 * This function is used internally by heur_gcd().
869 * @param e expanded multivariate polynomial
870 * @return maximum coefficient
873 numeric ex::max_coefficient(void) const
876 return bp->max_coefficient();
879 numeric basic::max_coefficient(void) const
884 numeric numeric::max_coefficient(void) const
889 numeric add::max_coefficient(void) const
891 epvector::const_iterator it = seq.begin();
892 epvector::const_iterator itend = seq.end();
893 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
894 numeric cur_max = abs(ex_to_numeric(overall_coeff));
895 while (it != itend) {
897 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
898 a = abs(ex_to_numeric(it->coeff));
906 numeric mul::max_coefficient(void) const
908 #ifdef DO_GINAC_ASSERT
909 epvector::const_iterator it = seq.begin();
910 epvector::const_iterator itend = seq.end();
911 while (it != itend) {
912 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
915 #endif // def DO_GINAC_ASSERT
916 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
917 return abs(ex_to_numeric(overall_coeff));
921 /** Apply symmetric modular homomorphism to a multivariate polynomial.
922 * This function is used internally by heur_gcd().
924 * @param e expanded multivariate polynomial
926 * @return mapped polynomial
929 ex ex::smod(const numeric &xi) const
935 ex basic::smod(const numeric &xi) const
940 ex numeric::smod(const numeric &xi) const
942 #ifndef NO_GINAC_NAMESPACE
943 return GiNaC::smod(*this, xi);
944 #else // ndef NO_GINAC_NAMESPACE
945 return ::smod(*this, xi);
946 #endif // ndef NO_GINAC_NAMESPACE
949 ex add::smod(const numeric &xi) const
952 newseq.reserve(seq.size()+1);
953 epvector::const_iterator it = seq.begin();
954 epvector::const_iterator itend = seq.end();
955 while (it != itend) {
956 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
957 #ifndef NO_GINAC_NAMESPACE
958 numeric coeff = GiNaC::smod(ex_to_numeric(it->coeff), xi);
959 #else // ndef NO_GINAC_NAMESPACE
960 numeric coeff = ::smod(ex_to_numeric(it->coeff), xi);
961 #endif // ndef NO_GINAC_NAMESPACE
962 if (!coeff.is_zero())
963 newseq.push_back(expair(it->rest, coeff));
966 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
967 #ifndef NO_GINAC_NAMESPACE
968 numeric coeff = GiNaC::smod(ex_to_numeric(overall_coeff), xi);
969 #else // ndef NO_GINAC_NAMESPACE
970 numeric coeff = ::smod(ex_to_numeric(overall_coeff), xi);
971 #endif // ndef NO_GINAC_NAMESPACE
972 return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
975 ex mul::smod(const numeric &xi) const
977 #ifdef DO_GINAC_ASSERT
978 epvector::const_iterator it = seq.begin();
979 epvector::const_iterator itend = seq.end();
980 while (it != itend) {
981 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
984 #endif // def DO_GINAC_ASSERT
985 mul * mulcopyp=new mul(*this);
986 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
987 #ifndef NO_GINAC_NAMESPACE
988 mulcopyp->overall_coeff = GiNaC::smod(ex_to_numeric(overall_coeff),xi);
989 #else // ndef NO_GINAC_NAMESPACE
990 mulcopyp->overall_coeff = ::smod(ex_to_numeric(overall_coeff),xi);
991 #endif // ndef NO_GINAC_NAMESPACE
992 mulcopyp->clearflag(status_flags::evaluated);
993 mulcopyp->clearflag(status_flags::hash_calculated);
994 return mulcopyp->setflag(status_flags::dynallocated);
998 /** Exception thrown by heur_gcd() to signal failure. */
999 class gcdheu_failed {};
1001 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1002 * get_symbol_stats() must have been called previously with the input
1003 * polynomials and an iterator to the first element of the sym_desc vector
1004 * passed in. This function is used internally by gcd().
1006 * @param a first multivariate polynomial (expanded)
1007 * @param b second multivariate polynomial (expanded)
1008 * @param ca cofactor of polynomial a (returned), NULL to suppress
1009 * calculation of cofactor
1010 * @param cb cofactor of polynomial b (returned), NULL to suppress
1011 * calculation of cofactor
1012 * @param var iterator to first element of vector of sym_desc structs
1013 * @return the GCD as a new expression
1015 * @exception gcdheu_failed() */
1017 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
1019 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1020 numeric g = gcd(ex_to_numeric(a), ex_to_numeric(b));
1025 *ca = ex_to_numeric(a).mul(rg);
1027 *cb = ex_to_numeric(b).mul(rg);
1031 // The first symbol is our main variable
1032 const symbol *x = var->sym;
1034 // Remove integer content
1035 numeric gc = gcd(a.integer_content(), b.integer_content());
1036 numeric rgc = gc.inverse();
1039 int maxdeg = max(p.degree(*x), q.degree(*x));
1041 // Find evaluation point
1042 numeric mp = p.max_coefficient(), mq = q.max_coefficient();
1045 xi = mq * _num2() + _num2();
1047 xi = mp * _num2() + _num2();
1050 for (int t=0; t<6; t++) {
1051 if (xi.int_length() * maxdeg > 50000)
1052 throw gcdheu_failed();
1054 // Apply evaluation homomorphism and calculate GCD
1055 ex gamma = heur_gcd(p.subs(*x == xi), q.subs(*x == xi), NULL, NULL, var+1).expand();
1056 if (!is_ex_exactly_of_type(gamma, fail)) {
1058 // Reconstruct polynomial from GCD of mapped polynomials
1060 numeric rxi = xi.inverse();
1061 for (int i=0; !gamma.is_zero(); i++) {
1062 ex gi = gamma.smod(xi);
1063 g += gi * power(*x, i);
1064 gamma = (gamma - gi) * rxi;
1066 // Remove integer content
1067 g /= g.integer_content();
1069 // If the calculated polynomial divides both a and b, this is the GCD
1071 if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1073 ex lc = g.lcoeff(*x);
1074 if (is_ex_exactly_of_type(lc, numeric) && lc.compare(_ex0()) < 0)
1081 // Next evaluation point
1082 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1084 return *new ex(fail());
1088 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1091 * @param a first multivariate polynomial
1092 * @param b second multivariate polynomial
1093 * @param check_args check whether a and b are polynomials with rational
1094 * coefficients (defaults to "true")
1095 * @return the GCD as a new expression */
1097 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1099 // Partially factored cases (to avoid expanding large expressions)
1100 if (is_ex_exactly_of_type(a, mul)) {
1101 if (is_ex_exactly_of_type(b, mul) && b.nops() > a.nops())
1107 for (int i=0; i<a.nops(); i++) {
1108 ex part_ca, part_cb;
1109 g *= gcd(a.op(i), part_b, &part_ca, &part_cb, check_args);
1118 } else if (is_ex_exactly_of_type(b, mul)) {
1119 if (is_ex_exactly_of_type(a, mul) && a.nops() > b.nops())
1125 for (int i=0; i<b.nops(); i++) {
1126 ex part_ca, part_cb;
1127 g *= gcd(part_a, b.op(i), &part_ca, &part_cb, check_args);
1138 // Some trivial cases
1139 ex aex = a.expand(), bex = b.expand();
1140 if (aex.is_zero()) {
1147 if (bex.is_zero()) {
1154 if (aex.is_equal(_ex1()) || bex.is_equal(_ex1())) {
1162 if (a.is_equal(b)) {
1170 if (is_ex_exactly_of_type(aex, numeric) && is_ex_exactly_of_type(bex, numeric)) {
1171 numeric g = gcd(ex_to_numeric(aex), ex_to_numeric(bex));
1173 *ca = ex_to_numeric(aex) / g;
1175 *cb = ex_to_numeric(bex) / g;
1178 if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)) {
1179 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1182 // Gather symbol statistics
1183 sym_desc_vec sym_stats;
1184 get_symbol_stats(a, b, sym_stats);
1186 // The symbol with least degree is our main variable
1187 sym_desc_vec::const_iterator var = sym_stats.begin();
1188 const symbol *x = var->sym;
1190 // Cancel trivial common factor
1191 int ldeg_a = var->ldeg_a;
1192 int ldeg_b = var->ldeg_b;
1193 int min_ldeg = min(ldeg_a, ldeg_b);
1195 ex common = power(*x, min_ldeg);
1196 //clog << "trivial common factor " << common << endl;
1197 return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1200 // Try to eliminate variables
1201 if (var->deg_a == 0) {
1202 //clog << "eliminating variable " << *x << " from b" << endl;
1203 ex c = bex.content(*x);
1204 ex g = gcd(aex, c, ca, cb, false);
1206 *cb *= bex.unit(*x) * bex.primpart(*x, c);
1208 } else if (var->deg_b == 0) {
1209 //clog << "eliminating variable " << *x << " from a" << endl;
1210 ex c = aex.content(*x);
1211 ex g = gcd(c, bex, ca, cb, false);
1213 *ca *= aex.unit(*x) * aex.primpart(*x, c);
1217 // Try heuristic algorithm first, fall back to PRS if that failed
1220 g = heur_gcd(aex, bex, ca, cb, var);
1221 } catch (gcdheu_failed) {
1222 g = *new ex(fail());
1224 if (is_ex_exactly_of_type(g, fail)) {
1225 //clog << "heuristics failed" << endl;
1226 g = sr_gcd(aex, bex, x);
1228 divide(aex, g, *ca, false);
1230 divide(bex, g, *cb, false);
1236 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1238 * @param a first multivariate polynomial
1239 * @param b second multivariate polynomial
1240 * @param check_args check whether a and b are polynomials with rational
1241 * coefficients (defaults to "true")
1242 * @return the LCM as a new expression */
1243 ex lcm(const ex &a, const ex &b, bool check_args)
1245 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
1246 return gcd(ex_to_numeric(a), ex_to_numeric(b));
1247 if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1248 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1251 ex g = gcd(a, b, &ca, &cb, false);
1257 * Square-free factorization
1260 // Univariate GCD of polynomials in Q[x] (used internally by sqrfree()).
1261 // a and b can be multivariate polynomials but they are treated as univariate polynomials in x.
1262 static ex univariate_gcd(const ex &a, const ex &b, const symbol &x)
1268 if (a.is_equal(_ex1()) || b.is_equal(_ex1()))
1270 if (is_ex_of_type(a, numeric) && is_ex_of_type(b, numeric))
1271 return gcd(ex_to_numeric(a), ex_to_numeric(b));
1272 if (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1273 throw(std::invalid_argument("univariate_gcd: arguments must be polynomials over the rationals"));
1275 // Euclidean algorithm
1277 if (a.degree(x) >= b.degree(x)) {
1285 r = rem(c, d, x, false);
1291 return d / d.lcoeff(x);
1295 /** Compute square-free factorization of multivariate polynomial a(x) using
1298 * @param a multivariate polynomial
1299 * @param x variable to factor in
1300 * @return factored polynomial */
1301 ex sqrfree(const ex &a, const symbol &x)
1306 ex c = univariate_gcd(a, b, x);
1308 if (c.is_equal(_ex1())) {
1312 ex y = quo(b, c, x);
1313 ex z = y - w.diff(x);
1314 while (!z.is_zero()) {
1315 ex g = univariate_gcd(w, z, x);
1323 return res * power(w, i);
1328 * Normal form of rational functions
1331 // Create a symbol for replacing the expression "e" (or return a previously
1332 // assigned symbol). The symbol is appended to sym_list and returned, the
1333 // expression is appended to repl_list.
1334 static ex replace_with_symbol(const ex &e, lst &sym_lst, lst &repl_lst)
1336 // Expression already in repl_lst? Then return the assigned symbol
1337 for (unsigned i=0; i<repl_lst.nops(); i++)
1338 if (repl_lst.op(i).is_equal(e))
1339 return sym_lst.op(i);
1341 // Otherwise create new symbol and add to list, taking care that the
1342 // replacement expression doesn't contain symbols from the sym_lst
1343 // because subs() is not recursive
1346 ex e_replaced = e.subs(sym_lst, repl_lst);
1348 repl_lst.append(e_replaced);
1353 /** Default implementation of ex::normal(). It replaces the object with a
1355 * @see ex::normal */
1356 ex basic::normal(lst &sym_lst, lst &repl_lst, int level) const
1358 return replace_with_symbol(*this, sym_lst, repl_lst);
1362 /** Implementation of ex::normal() for symbols. This returns the unmodifies symbol.
1363 * @see ex::normal */
1364 ex symbol::normal(lst &sym_lst, lst &repl_lst, int level) const
1370 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1371 * into re+I*im and replaces I and non-rational real numbers with a temporary
1373 * @see ex::normal */
1374 ex numeric::normal(lst &sym_lst, lst &repl_lst, int level) const
1380 return replace_with_symbol(*this, sym_lst, repl_lst);
1382 numeric re = real(), im = imag();
1383 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, sym_lst, repl_lst);
1384 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, sym_lst, repl_lst);
1385 return re_ex + im_ex * replace_with_symbol(I, sym_lst, repl_lst);
1390 /** Fraction cancellation.
1391 * @param n numerator
1392 * @param d denominator
1393 * @return cancelled fraction n/d */
1394 static ex frac_cancel(const ex &n, const ex &d)
1398 ex pre_factor = _ex1();
1400 // Handle special cases where numerator or denominator is 0
1403 if (den.expand().is_zero())
1404 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
1406 // More special cases
1407 if (is_ex_exactly_of_type(den, numeric))
1410 // Bring numerator and denominator to Z[X] by multiplying with
1411 // LCM of all coefficients' denominators
1412 ex num_lcm = lcm_of_coefficients_denominators(num);
1413 ex den_lcm = lcm_of_coefficients_denominators(den);
1414 num = multiply_lcm(num, num_lcm);
1415 den = multiply_lcm(den, den_lcm);
1416 pre_factor = den_lcm / num_lcm;
1418 // Cancel GCD from numerator and denominator
1420 if (gcd(num, den, &cnum, &cden, false) != _ex1()) {
1425 // Make denominator unit normal (i.e. coefficient of first symbol
1426 // as defined by get_first_symbol() is made positive)
1428 if (get_first_symbol(den, x)) {
1429 if (den.unit(*x).compare(_ex0()) < 0) {
1434 return pre_factor * num / den;
1438 /** Implementation of ex::normal() for a sum. It expands terms and performs
1439 * fractional addition.
1440 * @see ex::normal */
1441 ex add::normal(lst &sym_lst, lst &repl_lst, int level) const
1443 // Normalize and expand children
1445 o.reserve(seq.size()+1);
1446 epvector::const_iterator it = seq.begin(), itend = seq.end();
1447 while (it != itend) {
1448 ex n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1).expand();
1449 if (is_ex_exactly_of_type(n, add)) {
1450 epvector::const_iterator bit = (static_cast<add *>(n.bp))->seq.begin(), bitend = (static_cast<add *>(n.bp))->seq.end();
1451 while (bit != bitend) {
1452 o.push_back(recombine_pair_to_ex(*bit));
1455 o.push_back((static_cast<add *>(n.bp))->overall_coeff);
1460 o.push_back(overall_coeff.bp->normal(sym_lst, repl_lst, level-1));
1462 // Determine common denominator
1464 exvector::const_iterator ait = o.begin(), aitend = o.end();
1465 while (ait != aitend) {
1466 den = lcm((*ait).denom(false), den, false);
1471 if (den.is_equal(_ex1()))
1472 return (new add(o))->setflag(status_flags::dynallocated);
1475 for (ait=o.begin(); ait!=aitend; ait++) {
1477 if (!divide(den, (*ait).denom(false), q, false)) {
1478 // should not happen
1479 throw(std::runtime_error("invalid expression in add::normal, division failed"));
1481 num_seq.push_back((*ait).numer(false) * q);
1483 ex num = add(num_seq);
1485 // Cancel common factors from num/den
1486 return frac_cancel(num, den);
1491 /** Implementation of ex::normal() for a product. It cancels common factors
1493 * @see ex::normal() */
1494 ex mul::normal(lst &sym_lst, lst &repl_lst, int level) const
1496 // Normalize children
1498 o.reserve(seq.size()+1);
1499 epvector::const_iterator it = seq.begin(), itend = seq.end();
1500 while (it != itend) {
1501 o.push_back(recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1));
1504 o.push_back(overall_coeff.bp->normal(sym_lst, repl_lst, level-1));
1505 ex n = (new mul(o))->setflag(status_flags::dynallocated);
1506 return frac_cancel(n.numer(false), n.denom(false));
1510 /** Implementation of ex::normal() for powers. It normalizes the basis,
1511 * distributes integer exponents to numerator and denominator, and replaces
1512 * non-integer powers by temporary symbols.
1513 * @see ex::normal */
1514 ex power::normal(lst &sym_lst, lst &repl_lst, int level) const
1516 if (exponent.info(info_flags::integer)) {
1517 // Integer powers are distributed
1518 ex n = basis.bp->normal(sym_lst, repl_lst, level-1);
1519 ex num = n.numer(false);
1520 ex den = n.denom(false);
1521 return power(num, exponent) / power(den, exponent);
1523 // Non-integer powers are replaced by temporary symbol (after normalizing basis)
1524 ex n = power(basis.bp->normal(sym_lst, repl_lst, level-1), exponent);
1525 return replace_with_symbol(n, sym_lst, repl_lst);
1530 /** Implementation of ex::normal() for pseries. It normalizes each coefficient and
1531 * replaces the series by a temporary symbol.
1532 * @see ex::normal */
1533 ex pseries::normal(lst &sym_lst, lst &repl_lst, int level) const
1536 new_seq.reserve(seq.size());
1538 epvector::const_iterator it = seq.begin(), itend = seq.end();
1539 while (it != itend) {
1540 new_seq.push_back(expair(it->rest.normal(), it->coeff));
1544 ex n = pseries(var, point, new_seq);
1545 return replace_with_symbol(n, sym_lst, repl_lst);
1549 /** Normalization of rational functions.
1550 * This function converts an expression to its normal form
1551 * "numerator/denominator", where numerator and denominator are (relatively
1552 * prime) polynomials. Any subexpressions which are not rational functions
1553 * (like non-rational numbers, non-integer powers or functions like Sin(),
1554 * Cos() etc.) are replaced by temporary symbols which are re-substituted by
1555 * the (normalized) subexpressions before normal() returns (this way, any
1556 * expression can be treated as a rational function). normal() is applied
1557 * recursively to arguments of functions etc.
1559 * @param level maximum depth of recursion
1560 * @return normalized expression */
1561 ex ex::normal(int level) const
1563 lst sym_lst, repl_lst;
1564 ex e = bp->normal(sym_lst, repl_lst, level);
1565 if (sym_lst.nops() > 0)
1566 return e.subs(sym_lst, repl_lst);
1571 #ifndef NO_GINAC_NAMESPACE
1572 } // namespace GiNaC
1573 #endif // ndef NO_GINAC_NAMESPACE