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) || is_ex_exactly_of_type(e, mul)) {
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, power))
199 return lcmcoeff(e.op(0), l);
203 /** Compute LCM of denominators of coefficients of a polynomial.
204 * Given a polynomial with rational coefficients, this function computes
205 * the LCM of the denominators of all coefficients. This can be used
206 * To bring a polynomial from Q[X] to Z[X].
208 * @param e multivariate polynomial
209 * @return LCM of denominators of coefficients */
211 static numeric lcm_of_coefficients_denominators(const ex &e)
213 return lcmcoeff(e.expand(), _num1());
217 /** Compute the integer content (= GCD of all numeric coefficients) of an
218 * expanded polynomial.
220 * @param e expanded polynomial
221 * @return integer content */
223 numeric ex::integer_content(void) const
226 return bp->integer_content();
229 numeric basic::integer_content(void) const
234 numeric numeric::integer_content(void) const
239 numeric add::integer_content(void) const
241 epvector::const_iterator it = seq.begin();
242 epvector::const_iterator itend = seq.end();
244 while (it != itend) {
245 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
246 GINAC_ASSERT(is_ex_exactly_of_type(it->coeff,numeric));
247 c = gcd(ex_to_numeric(it->coeff), c);
250 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
251 c = gcd(ex_to_numeric(overall_coeff),c);
255 numeric mul::integer_content(void) const
257 #ifdef DO_GINAC_ASSERT
258 epvector::const_iterator it = seq.begin();
259 epvector::const_iterator itend = seq.end();
260 while (it != itend) {
261 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
264 #endif // def DO_GINAC_ASSERT
265 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
266 return abs(ex_to_numeric(overall_coeff));
271 * Polynomial quotients and remainders
274 /** Quotient q(x) of polynomials a(x) and b(x) in Q[x].
275 * It satisfies a(x)=b(x)*q(x)+r(x).
277 * @param a first polynomial in x (dividend)
278 * @param b second polynomial in x (divisor)
279 * @param x a and b are polynomials in x
280 * @param check_args check whether a and b are polynomials with rational
281 * coefficients (defaults to "true")
282 * @return quotient of a and b in Q[x] */
284 ex quo(const ex &a, const ex &b, const symbol &x, bool check_args)
287 throw(std::overflow_error("quo: division by zero"));
288 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
294 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
295 throw(std::invalid_argument("quo: arguments must be polynomials over the rationals"));
297 // Polynomial long division
302 int bdeg = b.degree(x);
303 int rdeg = r.degree(x);
304 ex blcoeff = b.expand().coeff(x, bdeg);
305 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
306 while (rdeg >= bdeg) {
307 ex term, rcoeff = r.coeff(x, rdeg);
308 if (blcoeff_is_numeric)
309 term = rcoeff / blcoeff;
311 if (!divide(rcoeff, blcoeff, term, false))
312 return *new ex(fail());
314 term *= power(x, rdeg - bdeg);
316 r -= (term * b).expand();
325 /** Remainder r(x) of polynomials a(x) and b(x) in Q[x].
326 * It satisfies a(x)=b(x)*q(x)+r(x).
328 * @param a first polynomial in x (dividend)
329 * @param b second polynomial in x (divisor)
330 * @param x a and b are polynomials in x
331 * @param check_args check whether a and b are polynomials with rational
332 * coefficients (defaults to "true")
333 * @return remainder of a(x) and b(x) in Q[x] */
335 ex rem(const ex &a, const ex &b, const symbol &x, bool check_args)
338 throw(std::overflow_error("rem: division by zero"));
339 if (is_ex_exactly_of_type(a, numeric)) {
340 if (is_ex_exactly_of_type(b, numeric))
349 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
350 throw(std::invalid_argument("rem: arguments must be polynomials over the rationals"));
352 // Polynomial long division
356 int bdeg = b.degree(x);
357 int rdeg = r.degree(x);
358 ex blcoeff = b.expand().coeff(x, bdeg);
359 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
360 while (rdeg >= bdeg) {
361 ex term, rcoeff = r.coeff(x, rdeg);
362 if (blcoeff_is_numeric)
363 term = rcoeff / blcoeff;
365 if (!divide(rcoeff, blcoeff, term, false))
366 return *new ex(fail());
368 term *= power(x, rdeg - bdeg);
369 r -= (term * b).expand();
378 /** Pseudo-remainder of polynomials a(x) and b(x) in Z[x].
380 * @param a first polynomial in x (dividend)
381 * @param b second polynomial in x (divisor)
382 * @param x a and b are polynomials in x
383 * @param check_args check whether a and b are polynomials with rational
384 * coefficients (defaults to "true")
385 * @return pseudo-remainder of a(x) and b(x) in Z[x] */
387 ex prem(const ex &a, const ex &b, const symbol &x, bool check_args)
390 throw(std::overflow_error("prem: division by zero"));
391 if (is_ex_exactly_of_type(a, numeric)) {
392 if (is_ex_exactly_of_type(b, numeric))
397 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
398 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
400 // Polynomial long division
403 int rdeg = r.degree(x);
404 int bdeg = eb.degree(x);
407 blcoeff = eb.coeff(x, bdeg);
411 eb -= blcoeff * power(x, bdeg);
415 int delta = rdeg - bdeg + 1, i = 0;
416 while (rdeg >= bdeg && !r.is_zero()) {
417 ex rlcoeff = r.coeff(x, rdeg);
418 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
422 r -= rlcoeff * power(x, rdeg);
423 r = (blcoeff * r).expand() - term;
427 return power(blcoeff, delta - i) * r;
431 /** Exact polynomial division of a(X) by b(X) in Q[X].
433 * @param a first multivariate polynomial (dividend)
434 * @param b second multivariate polynomial (divisor)
435 * @param q quotient (returned)
436 * @param check_args check whether a and b are polynomials with rational
437 * coefficients (defaults to "true")
438 * @return "true" when exact division succeeds (quotient returned in q),
439 * "false" otherwise */
441 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
445 throw(std::overflow_error("divide: division by zero"));
446 if (is_ex_exactly_of_type(b, numeric)) {
449 } else if (is_ex_exactly_of_type(a, numeric))
457 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
458 throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
462 if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
463 throw(std::invalid_argument("invalid expression in divide()"));
465 // Polynomial long division (recursive)
469 int bdeg = b.degree(*x);
470 int rdeg = r.degree(*x);
471 ex blcoeff = b.expand().coeff(*x, bdeg);
472 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
473 while (rdeg >= bdeg) {
474 ex term, rcoeff = r.coeff(*x, rdeg);
475 if (blcoeff_is_numeric)
476 term = rcoeff / blcoeff;
478 if (!divide(rcoeff, blcoeff, term, false))
480 term *= power(*x, rdeg - bdeg);
482 r -= (term * b).expand();
496 typedef pair<ex, ex> ex2;
497 typedef pair<ex, bool> exbool;
500 bool operator() (const ex2 p, const ex2 q) const
502 return p.first.compare(q.first) < 0 || (!(q.first.compare(p.first) < 0) && p.second.compare(q.second) < 0);
506 typedef map<ex2, exbool, ex2_less> ex2_exbool_remember;
510 /** Exact polynomial division of a(X) by b(X) in Z[X].
511 * This functions works like divide() but the input and output polynomials are
512 * in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
513 * divide(), it doesnĀ“t check whether the input polynomials really are integer
514 * polynomials, so be careful of what you pass in. Also, you have to run
515 * get_symbol_stats() over the input polynomials before calling this function
516 * and pass an iterator to the first element of the sym_desc vector. This
517 * function is used internally by the heur_gcd().
519 * @param a first multivariate polynomial (dividend)
520 * @param b second multivariate polynomial (divisor)
521 * @param q quotient (returned)
522 * @param var iterator to first element of vector of sym_desc structs
523 * @return "true" when exact division succeeds (the quotient is returned in
524 * q), "false" otherwise.
525 * @see get_symbol_stats, heur_gcd */
526 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
530 throw(std::overflow_error("divide_in_z: division by zero"));
531 if (b.is_equal(_ex1())) {
535 if (is_ex_exactly_of_type(a, numeric)) {
536 if (is_ex_exactly_of_type(b, numeric)) {
538 return q.info(info_flags::integer);
551 static ex2_exbool_remember dr_remember;
552 ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
553 if (remembered != dr_remember.end()) {
554 q = remembered->second.first;
555 return remembered->second.second;
560 const symbol *x = var->sym;
563 int adeg = a.degree(*x), bdeg = b.degree(*x);
569 // Polynomial long division (recursive)
575 ex blcoeff = eb.coeff(*x, bdeg);
576 while (rdeg >= bdeg) {
577 ex term, rcoeff = r.coeff(*x, rdeg);
578 if (!divide_in_z(rcoeff, blcoeff, term, var+1))
580 term = (term * power(*x, rdeg - bdeg)).expand();
582 r -= (term * eb).expand();
585 dr_remember[ex2(a, b)] = exbool(q, true);
592 dr_remember[ex2(a, b)] = exbool(q, false);
598 // Trial division using polynomial interpolation
601 // Compute values at evaluation points 0..adeg
602 vector<numeric> alpha; alpha.reserve(adeg + 1);
603 exvector u; u.reserve(adeg + 1);
604 numeric point = _num0();
606 for (i=0; i<=adeg; i++) {
607 ex bs = b.subs(*x == point);
608 while (bs.is_zero()) {
610 bs = b.subs(*x == point);
612 if (!divide_in_z(a.subs(*x == point), bs, c, var+1))
614 alpha.push_back(point);
620 vector<numeric> rcp; rcp.reserve(adeg + 1);
622 for (k=1; k<=adeg; k++) {
623 numeric product = alpha[k] - alpha[0];
625 product *= alpha[k] - alpha[i];
626 rcp.push_back(product.inverse());
629 // Compute Newton coefficients
630 exvector v; v.reserve(adeg + 1);
632 for (k=1; k<=adeg; k++) {
634 for (i=k-2; i>=0; i--)
635 temp = temp * (alpha[k] - alpha[i]) + v[i];
636 v.push_back((u[k] - temp) * rcp[k]);
639 // Convert from Newton form to standard form
641 for (k=adeg-1; k>=0; k--)
642 c = c * (*x - alpha[k]) + v[k];
644 if (c.degree(*x) == (adeg - bdeg)) {
654 * Separation of unit part, content part and primitive part of polynomials
657 /** Compute unit part (= sign of leading coefficient) of a multivariate
658 * polynomial in Z[x]. The product of unit part, content part, and primitive
659 * part is the polynomial itself.
661 * @param x variable in which to compute the unit part
663 * @see ex::content, ex::primpart */
664 ex ex::unit(const symbol &x) const
666 ex c = expand().lcoeff(x);
667 if (is_ex_exactly_of_type(c, numeric))
668 return c < _ex0() ? _ex_1() : _ex1();
671 if (get_first_symbol(c, y))
674 throw(std::invalid_argument("invalid expression in unit()"));
679 /** Compute content part (= unit normal GCD of all coefficients) of a
680 * multivariate polynomial in Z[x]. The product of unit part, content part,
681 * and primitive part is the polynomial itself.
683 * @param x variable in which to compute the content part
684 * @return content part
685 * @see ex::unit, ex::primpart */
686 ex ex::content(const symbol &x) const
690 if (is_ex_exactly_of_type(*this, numeric))
691 return info(info_flags::negative) ? -*this : *this;
696 // First, try the integer content
697 ex c = e.integer_content();
699 ex lcoeff = r.lcoeff(x);
700 if (lcoeff.info(info_flags::integer))
703 // GCD of all coefficients
704 int deg = e.degree(x);
705 int ldeg = e.ldegree(x);
707 return e.lcoeff(x) / e.unit(x);
709 for (int i=ldeg; i<=deg; i++)
710 c = gcd(e.coeff(x, i), c, NULL, NULL, false);
715 /** Compute primitive part of a multivariate polynomial in Z[x].
716 * The product of unit part, content part, and primitive part is the
719 * @param x variable in which to compute the primitive part
720 * @return primitive part
721 * @see ex::unit, ex::content */
722 ex ex::primpart(const symbol &x) const
726 if (is_ex_exactly_of_type(*this, numeric))
733 if (is_ex_exactly_of_type(c, numeric))
734 return *this / (c * u);
736 return quo(*this, c * u, x, false);
740 /** Compute primitive part of a multivariate polynomial in Z[x] when the
741 * content part is already known. This function is faster in computing the
742 * primitive part than the previous function.
744 * @param x variable in which to compute the primitive part
745 * @param c previously computed content part
746 * @return primitive part */
748 ex ex::primpart(const symbol &x, const ex &c) const
754 if (is_ex_exactly_of_type(*this, numeric))
758 if (is_ex_exactly_of_type(c, numeric))
759 return *this / (c * u);
761 return quo(*this, c * u, x, false);
766 * GCD of multivariate polynomials
769 /** Compute GCD of multivariate polynomials using the subresultant PRS
770 * algorithm. This function is used internally gy gcd().
772 * @param a first multivariate polynomial
773 * @param b second multivariate polynomial
774 * @param x pointer to symbol (main variable) in which to compute the GCD in
775 * @return the GCD as a new expression
778 static ex sr_gcd(const ex &a, const ex &b, const symbol *x)
780 // Sort c and d so that c has higher degree
782 int adeg = a.degree(*x), bdeg = b.degree(*x);
796 // Remove content from c and d, to be attached to GCD later
797 ex cont_c = c.content(*x);
798 ex cont_d = d.content(*x);
799 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
802 c = c.primpart(*x, cont_c);
803 d = d.primpart(*x, cont_d);
805 // First element of subresultant sequence
806 ex r = _ex0(), ri = _ex1(), psi = _ex1();
807 int delta = cdeg - ddeg;
810 // Calculate polynomial pseudo-remainder
811 r = prem(c, d, *x, false);
813 return gamma * d.primpart(*x);
816 if (!divide(r, ri * power(psi, delta), d, false))
817 throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
820 if (is_ex_exactly_of_type(r, numeric))
823 return gamma * r.primpart(*x);
826 // Next element of subresultant sequence
827 ri = c.expand().lcoeff(*x);
831 divide(power(ri, delta), power(psi, delta-1), psi, false);
837 /** Return maximum (absolute value) coefficient of a polynomial.
838 * This function is used internally by heur_gcd().
840 * @param e expanded multivariate polynomial
841 * @return maximum coefficient
844 numeric ex::max_coefficient(void) const
847 return bp->max_coefficient();
850 numeric basic::max_coefficient(void) const
855 numeric numeric::max_coefficient(void) const
860 numeric add::max_coefficient(void) const
862 epvector::const_iterator it = seq.begin();
863 epvector::const_iterator itend = seq.end();
864 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
865 numeric cur_max = abs(ex_to_numeric(overall_coeff));
866 while (it != itend) {
868 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
869 a = abs(ex_to_numeric(it->coeff));
877 numeric mul::max_coefficient(void) const
879 #ifdef DO_GINAC_ASSERT
880 epvector::const_iterator it = seq.begin();
881 epvector::const_iterator itend = seq.end();
882 while (it != itend) {
883 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
886 #endif // def DO_GINAC_ASSERT
887 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
888 return abs(ex_to_numeric(overall_coeff));
892 /** Apply symmetric modular homomorphism to a multivariate polynomial.
893 * This function is used internally by heur_gcd().
895 * @param e expanded multivariate polynomial
897 * @return mapped polynomial
900 ex ex::smod(const numeric &xi) const
906 ex basic::smod(const numeric &xi) const
911 ex numeric::smod(const numeric &xi) const
913 #ifndef NO_GINAC_NAMESPACE
914 return GiNaC::smod(*this, xi);
915 #else // ndef NO_GINAC_NAMESPACE
916 return ::smod(*this, xi);
917 #endif // ndef NO_GINAC_NAMESPACE
920 ex add::smod(const numeric &xi) const
923 newseq.reserve(seq.size()+1);
924 epvector::const_iterator it = seq.begin();
925 epvector::const_iterator itend = seq.end();
926 while (it != itend) {
927 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
928 #ifndef NO_GINAC_NAMESPACE
929 numeric coeff = GiNaC::smod(ex_to_numeric(it->coeff), xi);
930 #else // ndef NO_GINAC_NAMESPACE
931 numeric coeff = ::smod(ex_to_numeric(it->coeff), xi);
932 #endif // ndef NO_GINAC_NAMESPACE
933 if (!coeff.is_zero())
934 newseq.push_back(expair(it->rest, coeff));
937 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
938 #ifndef NO_GINAC_NAMESPACE
939 numeric coeff = GiNaC::smod(ex_to_numeric(overall_coeff), xi);
940 #else // ndef NO_GINAC_NAMESPACE
941 numeric coeff = ::smod(ex_to_numeric(overall_coeff), xi);
942 #endif // ndef NO_GINAC_NAMESPACE
943 return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
946 ex mul::smod(const numeric &xi) const
948 #ifdef DO_GINAC_ASSERT
949 epvector::const_iterator it = seq.begin();
950 epvector::const_iterator itend = seq.end();
951 while (it != itend) {
952 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
955 #endif // def DO_GINAC_ASSERT
956 mul * mulcopyp=new mul(*this);
957 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
958 #ifndef NO_GINAC_NAMESPACE
959 mulcopyp->overall_coeff = GiNaC::smod(ex_to_numeric(overall_coeff),xi);
960 #else // ndef NO_GINAC_NAMESPACE
961 mulcopyp->overall_coeff = ::smod(ex_to_numeric(overall_coeff),xi);
962 #endif // ndef NO_GINAC_NAMESPACE
963 mulcopyp->clearflag(status_flags::evaluated);
964 mulcopyp->clearflag(status_flags::hash_calculated);
965 return mulcopyp->setflag(status_flags::dynallocated);
969 /** Exception thrown by heur_gcd() to signal failure. */
970 class gcdheu_failed {};
972 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
973 * get_symbol_stats() must have been called previously with the input
974 * polynomials and an iterator to the first element of the sym_desc vector
975 * passed in. This function is used internally by gcd().
977 * @param a first multivariate polynomial (expanded)
978 * @param b second multivariate polynomial (expanded)
979 * @param ca cofactor of polynomial a (returned), NULL to suppress
980 * calculation of cofactor
981 * @param cb cofactor of polynomial b (returned), NULL to suppress
982 * calculation of cofactor
983 * @param var iterator to first element of vector of sym_desc structs
984 * @return the GCD as a new expression
986 * @exception gcdheu_failed() */
988 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
990 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
991 numeric g = gcd(ex_to_numeric(a), ex_to_numeric(b));
996 *ca = ex_to_numeric(a).mul(rg);
998 *cb = ex_to_numeric(b).mul(rg);
1002 // The first symbol is our main variable
1003 const symbol *x = var->sym;
1005 // Remove integer content
1006 numeric gc = gcd(a.integer_content(), b.integer_content());
1007 numeric rgc = gc.inverse();
1010 int maxdeg = max(p.degree(*x), q.degree(*x));
1012 // Find evaluation point
1013 numeric mp = p.max_coefficient(), mq = q.max_coefficient();
1016 xi = mq * _num2() + _num2();
1018 xi = mp * _num2() + _num2();
1021 for (int t=0; t<6; t++) {
1022 if (xi.int_length() * maxdeg > 50000)
1023 throw gcdheu_failed();
1025 // Apply evaluation homomorphism and calculate GCD
1026 ex gamma = heur_gcd(p.subs(*x == xi), q.subs(*x == xi), NULL, NULL, var+1).expand();
1027 if (!is_ex_exactly_of_type(gamma, fail)) {
1029 // Reconstruct polynomial from GCD of mapped polynomials
1031 numeric rxi = xi.inverse();
1032 for (int i=0; !gamma.is_zero(); i++) {
1033 ex gi = gamma.smod(xi);
1034 g += gi * power(*x, i);
1035 gamma = (gamma - gi) * rxi;
1037 // Remove integer content
1038 g /= g.integer_content();
1040 // If the calculated polynomial divides both a and b, this is the GCD
1042 if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1044 ex lc = g.lcoeff(*x);
1045 if (is_ex_exactly_of_type(lc, numeric) && lc.compare(_ex0()) < 0)
1052 // Next evaluation point
1053 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1055 return *new ex(fail());
1059 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1062 * @param a first multivariate polynomial
1063 * @param b second multivariate polynomial
1064 * @param check_args check whether a and b are polynomials with rational
1065 * coefficients (defaults to "true")
1066 * @return the GCD as a new expression */
1068 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1070 // Some trivial cases
1071 ex aex = a.expand(), bex = b.expand();
1072 if (aex.is_zero()) {
1079 if (bex.is_zero()) {
1086 if (aex.is_equal(_ex1()) || bex.is_equal(_ex1())) {
1094 if (a.is_equal(b)) {
1102 if (is_ex_exactly_of_type(aex, numeric) && is_ex_exactly_of_type(bex, numeric)) {
1103 numeric g = gcd(ex_to_numeric(aex), ex_to_numeric(bex));
1105 *ca = ex_to_numeric(aex) / g;
1107 *cb = ex_to_numeric(bex) / g;
1110 if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)) {
1111 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1114 // Gather symbol statistics
1115 sym_desc_vec sym_stats;
1116 get_symbol_stats(a, b, sym_stats);
1118 // The symbol with least degree is our main variable
1119 sym_desc_vec::const_iterator var = sym_stats.begin();
1120 const symbol *x = var->sym;
1122 // Cancel trivial common factor
1123 int ldeg_a = var->ldeg_a;
1124 int ldeg_b = var->ldeg_b;
1125 int min_ldeg = min(ldeg_a, ldeg_b);
1127 ex common = power(*x, min_ldeg);
1128 //clog << "trivial common factor " << common << endl;
1129 return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1132 // Try to eliminate variables
1133 if (var->deg_a == 0) {
1134 //clog << "eliminating variable " << *x << " from b" << endl;
1135 ex c = bex.content(*x);
1136 ex g = gcd(aex, c, ca, cb, false);
1138 *cb *= bex.unit(*x) * bex.primpart(*x, c);
1140 } else if (var->deg_b == 0) {
1141 //clog << "eliminating variable " << *x << " from a" << endl;
1142 ex c = aex.content(*x);
1143 ex g = gcd(c, bex, ca, cb, false);
1145 *ca *= aex.unit(*x) * aex.primpart(*x, c);
1149 // Try heuristic algorithm first, fall back to PRS if that failed
1152 g = heur_gcd(aex, bex, ca, cb, var);
1153 } catch (gcdheu_failed) {
1154 g = *new ex(fail());
1156 if (is_ex_exactly_of_type(g, fail)) {
1157 // clog << "heuristics failed" << endl;
1158 g = sr_gcd(aex, bex, x);
1160 divide(aex, g, *ca, false);
1162 divide(bex, g, *cb, false);
1168 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1170 * @param a first multivariate polynomial
1171 * @param b second multivariate polynomial
1172 * @param check_args check whether a and b are polynomials with rational
1173 * coefficients (defaults to "true")
1174 * @return the LCM as a new expression */
1175 ex lcm(const ex &a, const ex &b, bool check_args)
1177 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
1178 return gcd(ex_to_numeric(a), ex_to_numeric(b));
1179 if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1180 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1183 ex g = gcd(a, b, &ca, &cb, false);
1189 * Square-free factorization
1192 // Univariate GCD of polynomials in Q[x] (used internally by sqrfree()).
1193 // a and b can be multivariate polynomials but they are treated as univariate polynomials in x.
1194 static ex univariate_gcd(const ex &a, const ex &b, const symbol &x)
1200 if (a.is_equal(_ex1()) || b.is_equal(_ex1()))
1202 if (is_ex_of_type(a, numeric) && is_ex_of_type(b, numeric))
1203 return gcd(ex_to_numeric(a), ex_to_numeric(b));
1204 if (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1205 throw(std::invalid_argument("univariate_gcd: arguments must be polynomials over the rationals"));
1207 // Euclidean algorithm
1209 if (a.degree(x) >= b.degree(x)) {
1217 r = rem(c, d, x, false);
1223 return d / d.lcoeff(x);
1227 /** Compute square-free factorization of multivariate polynomial a(x) using
1230 * @param a multivariate polynomial
1231 * @param x variable to factor in
1232 * @return factored polynomial */
1233 ex sqrfree(const ex &a, const symbol &x)
1238 ex c = univariate_gcd(a, b, x);
1240 if (c.is_equal(_ex1())) {
1244 ex y = quo(b, c, x);
1245 ex z = y - w.diff(x);
1246 while (!z.is_zero()) {
1247 ex g = univariate_gcd(w, z, x);
1255 return res * power(w, i);
1260 * Normal form of rational functions
1263 // Create a symbol for replacing the expression "e" (or return a previously
1264 // assigned symbol). The symbol is appended to sym_list and returned, the
1265 // expression is appended to repl_list.
1266 static ex replace_with_symbol(const ex &e, lst &sym_lst, lst &repl_lst)
1268 // Expression already in repl_lst? Then return the assigned symbol
1269 for (unsigned i=0; i<repl_lst.nops(); i++)
1270 if (repl_lst.op(i).is_equal(e))
1271 return sym_lst.op(i);
1273 // Otherwise create new symbol and add to list, taking care that the
1274 // replacement expression doesn't contain symbols from the sym_lst
1275 // because subs() is not recursive
1278 ex e_replaced = e.subs(sym_lst, repl_lst);
1280 repl_lst.append(e_replaced);
1285 /** Default implementation of ex::normal(). It replaces the object with a
1287 * @see ex::normal */
1288 ex basic::normal(lst &sym_lst, lst &repl_lst, int level) const
1290 return replace_with_symbol(*this, sym_lst, repl_lst);
1294 /** Implementation of ex::normal() for symbols. This returns the unmodifies symbol.
1295 * @see ex::normal */
1296 ex symbol::normal(lst &sym_lst, lst &repl_lst, int level) const
1302 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1303 * into re+I*im and replaces I and non-rational real numbers with a temporary
1305 * @see ex::normal */
1306 ex numeric::normal(lst &sym_lst, lst &repl_lst, int level) const
1312 return replace_with_symbol(*this, sym_lst, repl_lst);
1314 numeric re = real(), im = imag();
1315 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, sym_lst, repl_lst);
1316 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, sym_lst, repl_lst);
1317 return re_ex + im_ex * replace_with_symbol(I, sym_lst, repl_lst);
1323 * Helper function for fraction cancellation (returns cancelled fraction n/d)
1325 static ex frac_cancel(const ex &n, const ex &d)
1329 ex pre_factor = _ex1();
1331 // Handle special cases where numerator or denominator is 0
1334 if (den.expand().is_zero())
1335 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
1337 // More special cases
1338 if (is_ex_exactly_of_type(den, numeric))
1343 // Bring numerator and denominator to Z[X] by multiplying with
1344 // LCM of all coefficients' denominators
1345 ex num_lcm = lcm_of_coefficients_denominators(num);
1346 ex den_lcm = lcm_of_coefficients_denominators(den);
1349 pre_factor = den_lcm / num_lcm;
1351 // Cancel GCD from numerator and denominator
1353 if (gcd(num, den, &cnum, &cden, false) != _ex1()) {
1358 // Make denominator unit normal (i.e. coefficient of first symbol
1359 // as defined by get_first_symbol() is made positive)
1361 if (get_first_symbol(den, x)) {
1362 if (den.unit(*x).compare(_ex0()) < 0) {
1367 return pre_factor * num / den;
1371 /** Implementation of ex::normal() for a sum. It expands terms and performs
1372 * fractional addition.
1373 * @see ex::normal */
1374 ex add::normal(lst &sym_lst, lst &repl_lst, int level) const
1376 // Normalize and expand children
1378 o.reserve(seq.size()+1);
1379 epvector::const_iterator it = seq.begin(), itend = seq.end();
1380 while (it != itend) {
1381 ex n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1).expand();
1382 if (is_ex_exactly_of_type(n, add)) {
1383 epvector::const_iterator bit = (static_cast<add *>(n.bp))->seq.begin(), bitend = (static_cast<add *>(n.bp))->seq.end();
1384 while (bit != bitend) {
1385 o.push_back(recombine_pair_to_ex(*bit));
1388 o.push_back((static_cast<add *>(n.bp))->overall_coeff);
1393 o.push_back(overall_coeff.bp->normal(sym_lst, repl_lst, level-1));
1395 // Determine common denominator
1397 exvector::const_iterator ait = o.begin(), aitend = o.end();
1398 while (ait != aitend) {
1399 den = lcm((*ait).denom(false), den, false);
1404 if (den.is_equal(_ex1()))
1405 return (new add(o))->setflag(status_flags::dynallocated);
1408 for (ait=o.begin(); ait!=aitend; ait++) {
1410 if (!divide(den, (*ait).denom(false), q, false)) {
1411 // should not happen
1412 throw(std::runtime_error("invalid expression in add::normal, division failed"));
1414 num_seq.push_back((*ait).numer(false) * q);
1416 ex num = add(num_seq);
1418 // Cancel common factors from num/den
1419 return frac_cancel(num, den);
1424 /** Implementation of ex::normal() for a product. It cancels common factors
1426 * @see ex::normal() */
1427 ex mul::normal(lst &sym_lst, lst &repl_lst, int level) const
1429 // Normalize children
1431 o.reserve(seq.size()+1);
1432 epvector::const_iterator it = seq.begin(), itend = seq.end();
1433 while (it != itend) {
1434 o.push_back(recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1));
1437 o.push_back(overall_coeff.bp->normal(sym_lst, repl_lst, level-1));
1438 ex n = (new mul(o))->setflag(status_flags::dynallocated);
1439 return frac_cancel(n.numer(false), n.denom(false));
1443 /** Implementation of ex::normal() for powers. It normalizes the basis,
1444 * distributes integer exponents to numerator and denominator, and replaces
1445 * non-integer powers by temporary symbols.
1446 * @see ex::normal */
1447 ex power::normal(lst &sym_lst, lst &repl_lst, int level) const
1449 if (exponent.info(info_flags::integer)) {
1450 // Integer powers are distributed
1451 ex n = basis.bp->normal(sym_lst, repl_lst, level-1);
1452 ex num = n.numer(false);
1453 ex den = n.denom(false);
1454 return power(num, exponent) / power(den, exponent);
1456 // Non-integer powers are replaced by temporary symbol (after normalizing basis)
1457 ex n = power(basis.bp->normal(sym_lst, repl_lst, level-1), exponent);
1458 return replace_with_symbol(n, sym_lst, repl_lst);
1463 /** Implementation of ex::normal() for pseries. It normalizes each coefficient and
1464 * replaces the series by a temporary symbol.
1465 * @see ex::normal */
1466 ex pseries::normal(lst &sym_lst, lst &repl_lst, int level) const
1469 new_seq.reserve(seq.size());
1471 epvector::const_iterator it = seq.begin(), itend = seq.end();
1472 while (it != itend) {
1473 new_seq.push_back(expair(it->rest.normal(), it->coeff));
1477 ex n = pseries(var, point, new_seq);
1478 return replace_with_symbol(n, sym_lst, repl_lst);
1482 /** Normalization of rational functions.
1483 * This function converts an expression to its normal form
1484 * "numerator/denominator", where numerator and denominator are (relatively
1485 * prime) polynomials. Any subexpressions which are not rational functions
1486 * (like non-rational numbers, non-integer powers or functions like Sin(),
1487 * Cos() etc.) are replaced by temporary symbols which are re-substituted by
1488 * the (normalized) subexpressions before normal() returns (this way, any
1489 * expression can be treated as a rational function). normal() is applied
1490 * recursively to arguments of functions etc.
1492 * @param level maximum depth of recursion
1493 * @return normalized expression */
1494 ex ex::normal(int level) const
1496 lst sym_lst, repl_lst;
1497 ex e = bp->normal(sym_lst, repl_lst, level);
1498 if (sym_lst.nops() > 0)
1499 return e.subs(sym_lst, repl_lst);
1504 #ifndef NO_GINAC_NAMESPACE
1505 } // namespace GiNaC
1506 #endif // ndef NO_GINAC_NAMESPACE