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 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 (int 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 (int 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 (int i=0; i<e.nops(); i++) {
196 c = lcmcoeff(e.op(i), c);
199 } else if (is_ex_exactly_of_type(e, power))
200 return lcmcoeff(e.op(0), l);
204 /** Compute LCM of denominators of coefficients of a polynomial.
205 * Given a polynomial with rational coefficients, this function computes
206 * the LCM of the denominators of all coefficients. This can be used
207 * To bring a polynomial from Q[X] to Z[X].
209 * @param e multivariate polynomial
210 * @return LCM of denominators of coefficients */
212 static numeric lcm_of_coefficients_denominators(const ex &e)
214 return lcmcoeff(e.expand(), _num1());
218 /** Compute the integer content (= GCD of all numeric coefficients) of an
219 * expanded polynomial.
221 * @param e expanded polynomial
222 * @return integer content */
224 numeric ex::integer_content(void) const
227 return bp->integer_content();
230 numeric basic::integer_content(void) const
235 numeric numeric::integer_content(void) const
240 numeric add::integer_content(void) const
242 epvector::const_iterator it = seq.begin();
243 epvector::const_iterator itend = seq.end();
245 while (it != itend) {
246 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
247 GINAC_ASSERT(is_ex_exactly_of_type(it->coeff,numeric));
248 c = gcd(ex_to_numeric(it->coeff), c);
251 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
252 c = gcd(ex_to_numeric(overall_coeff),c);
256 numeric mul::integer_content(void) const
258 #ifdef DO_GINAC_ASSERT
259 epvector::const_iterator it = seq.begin();
260 epvector::const_iterator itend = seq.end();
261 while (it != itend) {
262 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
265 #endif // def DO_GINAC_ASSERT
266 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
267 return abs(ex_to_numeric(overall_coeff));
272 * Polynomial quotients and remainders
275 /** Quotient q(x) of polynomials a(x) and b(x) in Q[x].
276 * It satisfies a(x)=b(x)*q(x)+r(x).
278 * @param a first polynomial in x (dividend)
279 * @param b second polynomial in x (divisor)
280 * @param x a and b are polynomials in x
281 * @param check_args check whether a and b are polynomials with rational
282 * coefficients (defaults to "true")
283 * @return quotient of a and b in Q[x] */
285 ex quo(const ex &a, const ex &b, const symbol &x, bool check_args)
288 throw(std::overflow_error("quo: division by zero"));
289 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
295 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
296 throw(std::invalid_argument("quo: arguments must be polynomials over the rationals"));
298 // Polynomial long division
303 int bdeg = b.degree(x);
304 int rdeg = r.degree(x);
305 ex blcoeff = b.expand().coeff(x, bdeg);
306 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
307 while (rdeg >= bdeg) {
308 ex term, rcoeff = r.coeff(x, rdeg);
309 if (blcoeff_is_numeric)
310 term = rcoeff / blcoeff;
312 if (!divide(rcoeff, blcoeff, term, false))
313 return *new ex(fail());
315 term *= power(x, rdeg - bdeg);
317 r -= (term * b).expand();
326 /** Remainder r(x) of polynomials a(x) and b(x) in Q[x].
327 * It satisfies a(x)=b(x)*q(x)+r(x).
329 * @param a first polynomial in x (dividend)
330 * @param b second polynomial in x (divisor)
331 * @param x a and b are polynomials in x
332 * @param check_args check whether a and b are polynomials with rational
333 * coefficients (defaults to "true")
334 * @return remainder of a(x) and b(x) in Q[x] */
336 ex rem(const ex &a, const ex &b, const symbol &x, bool check_args)
339 throw(std::overflow_error("rem: division by zero"));
340 if (is_ex_exactly_of_type(a, numeric)) {
341 if (is_ex_exactly_of_type(b, numeric))
350 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
351 throw(std::invalid_argument("rem: arguments must be polynomials over the rationals"));
353 // Polynomial long division
357 int bdeg = b.degree(x);
358 int rdeg = r.degree(x);
359 ex blcoeff = b.expand().coeff(x, bdeg);
360 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
361 while (rdeg >= bdeg) {
362 ex term, rcoeff = r.coeff(x, rdeg);
363 if (blcoeff_is_numeric)
364 term = rcoeff / blcoeff;
366 if (!divide(rcoeff, blcoeff, term, false))
367 return *new ex(fail());
369 term *= power(x, rdeg - bdeg);
370 r -= (term * b).expand();
379 /** Pseudo-remainder of polynomials a(x) and b(x) in Z[x].
381 * @param a first polynomial in x (dividend)
382 * @param b second polynomial in x (divisor)
383 * @param x a and b are polynomials in x
384 * @param check_args check whether a and b are polynomials with rational
385 * coefficients (defaults to "true")
386 * @return pseudo-remainder of a(x) and b(x) in Z[x] */
388 ex prem(const ex &a, const ex &b, const symbol &x, bool check_args)
391 throw(std::overflow_error("prem: division by zero"));
392 if (is_ex_exactly_of_type(a, numeric)) {
393 if (is_ex_exactly_of_type(b, numeric))
398 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
399 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
401 // Polynomial long division
404 int rdeg = r.degree(x);
405 int bdeg = eb.degree(x);
408 blcoeff = eb.coeff(x, bdeg);
412 eb -= blcoeff * power(x, bdeg);
416 int delta = rdeg - bdeg + 1, i = 0;
417 while (rdeg >= bdeg && !r.is_zero()) {
418 ex rlcoeff = r.coeff(x, rdeg);
419 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
423 r -= rlcoeff * power(x, rdeg);
424 r = (blcoeff * r).expand() - term;
428 return power(blcoeff, delta - i) * r;
432 /** Exact polynomial division of a(X) by b(X) in Q[X].
434 * @param a first multivariate polynomial (dividend)
435 * @param b second multivariate polynomial (divisor)
436 * @param q quotient (returned)
437 * @param check_args check whether a and b are polynomials with rational
438 * coefficients (defaults to "true")
439 * @return "true" when exact division succeeds (quotient returned in q),
440 * "false" otherwise */
442 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
446 throw(std::overflow_error("divide: division by zero"));
447 if (is_ex_exactly_of_type(b, numeric)) {
450 } else if (is_ex_exactly_of_type(a, numeric))
458 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
459 throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
463 if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
464 throw(std::invalid_argument("invalid expression in divide()"));
466 // Polynomial long division (recursive)
470 int bdeg = b.degree(*x);
471 int rdeg = r.degree(*x);
472 ex blcoeff = b.expand().coeff(*x, bdeg);
473 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
474 while (rdeg >= bdeg) {
475 ex term, rcoeff = r.coeff(*x, rdeg);
476 if (blcoeff_is_numeric)
477 term = rcoeff / blcoeff;
479 if (!divide(rcoeff, blcoeff, term, false))
481 term *= power(*x, rdeg - bdeg);
483 r -= (term * b).expand();
497 typedef pair<ex, ex> ex2;
498 typedef pair<ex, bool> exbool;
501 bool operator() (const ex2 p, const ex2 q) const
503 return p.first.compare(q.first) < 0 || (!(q.first.compare(p.first) < 0) && p.second.compare(q.second) < 0);
507 typedef map<ex2, exbool, ex2_less> ex2_exbool_remember;
511 /** Exact polynomial division of a(X) by b(X) in Z[X].
512 * This functions works like divide() but the input and output polynomials are
513 * in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
514 * divide(), it doesnĀ“t check whether the input polynomials really are integer
515 * polynomials, so be careful of what you pass in. Also, you have to run
516 * get_symbol_stats() over the input polynomials before calling this function
517 * and pass an iterator to the first element of the sym_desc vector. This
518 * function is used internally by the heur_gcd().
520 * @param a first multivariate polynomial (dividend)
521 * @param b second multivariate polynomial (divisor)
522 * @param q quotient (returned)
523 * @param var iterator to first element of vector of sym_desc structs
524 * @return "true" when exact division succeeds (the quotient is returned in
525 * q), "false" otherwise.
526 * @see get_symbol_stats, heur_gcd */
527 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
531 throw(std::overflow_error("divide_in_z: division by zero"));
532 if (b.is_equal(_ex1())) {
536 if (is_ex_exactly_of_type(a, numeric)) {
537 if (is_ex_exactly_of_type(b, numeric)) {
539 return q.info(info_flags::integer);
552 static ex2_exbool_remember dr_remember;
553 ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
554 if (remembered != dr_remember.end()) {
555 q = remembered->second.first;
556 return remembered->second.second;
561 const symbol *x = var->sym;
564 int adeg = a.degree(*x), bdeg = b.degree(*x);
570 // Polynomial long division (recursive)
576 ex blcoeff = eb.coeff(*x, bdeg);
577 while (rdeg >= bdeg) {
578 ex term, rcoeff = r.coeff(*x, rdeg);
579 if (!divide_in_z(rcoeff, blcoeff, term, var+1))
581 term = (term * power(*x, rdeg - bdeg)).expand();
583 r -= (term * eb).expand();
586 dr_remember[ex2(a, b)] = exbool(q, true);
593 dr_remember[ex2(a, b)] = exbool(q, false);
599 // Trial division using polynomial interpolation
602 // Compute values at evaluation points 0..adeg
603 vector<numeric> alpha; alpha.reserve(adeg + 1);
604 exvector u; u.reserve(adeg + 1);
605 numeric point = _num0();
607 for (i=0; i<=adeg; i++) {
608 ex bs = b.subs(*x == point);
609 while (bs.is_zero()) {
611 bs = b.subs(*x == point);
613 if (!divide_in_z(a.subs(*x == point), bs, c, var+1))
615 alpha.push_back(point);
621 vector<numeric> rcp; rcp.reserve(adeg + 1);
623 for (k=1; k<=adeg; k++) {
624 numeric product = alpha[k] - alpha[0];
626 product *= alpha[k] - alpha[i];
627 rcp.push_back(product.inverse());
630 // Compute Newton coefficients
631 exvector v; v.reserve(adeg + 1);
633 for (k=1; k<=adeg; k++) {
635 for (i=k-2; i>=0; i--)
636 temp = temp * (alpha[k] - alpha[i]) + v[i];
637 v.push_back((u[k] - temp) * rcp[k]);
640 // Convert from Newton form to standard form
642 for (k=adeg-1; k>=0; k--)
643 c = c * (*x - alpha[k]) + v[k];
645 if (c.degree(*x) == (adeg - bdeg)) {
655 * Separation of unit part, content part and primitive part of polynomials
658 /** Compute unit part (= sign of leading coefficient) of a multivariate
659 * polynomial in Z[x]. The product of unit part, content part, and primitive
660 * part is the polynomial itself.
662 * @param x variable in which to compute the unit part
664 * @see ex::content, ex::primpart */
665 ex ex::unit(const symbol &x) const
667 ex c = expand().lcoeff(x);
668 if (is_ex_exactly_of_type(c, numeric))
669 return c < _ex0() ? _ex_1() : _ex1();
672 if (get_first_symbol(c, y))
675 throw(std::invalid_argument("invalid expression in unit()"));
680 /** Compute content part (= unit normal GCD of all coefficients) of a
681 * multivariate polynomial in Z[x]. The product of unit part, content part,
682 * and primitive part is the polynomial itself.
684 * @param x variable in which to compute the content part
685 * @return content part
686 * @see ex::unit, ex::primpart */
687 ex ex::content(const symbol &x) const
691 if (is_ex_exactly_of_type(*this, numeric))
692 return info(info_flags::negative) ? -*this : *this;
697 // First, try the integer content
698 ex c = e.integer_content();
700 ex lcoeff = r.lcoeff(x);
701 if (lcoeff.info(info_flags::integer))
704 // GCD of all coefficients
705 int deg = e.degree(x);
706 int ldeg = e.ldegree(x);
708 return e.lcoeff(x) / e.unit(x);
710 for (int i=ldeg; i<=deg; i++)
711 c = gcd(e.coeff(x, i), c, NULL, NULL, false);
716 /** Compute primitive part of a multivariate polynomial in Z[x].
717 * The product of unit part, content part, and primitive part is the
720 * @param x variable in which to compute the primitive part
721 * @return primitive part
722 * @see ex::unit, ex::content */
723 ex ex::primpart(const symbol &x) const
727 if (is_ex_exactly_of_type(*this, numeric))
734 if (is_ex_exactly_of_type(c, numeric))
735 return *this / (c * u);
737 return quo(*this, c * u, x, false);
741 /** Compute primitive part of a multivariate polynomial in Z[x] when the
742 * content part is already known. This function is faster in computing the
743 * primitive part than the previous function.
745 * @param x variable in which to compute the primitive part
746 * @param c previously computed content part
747 * @return primitive part */
749 ex ex::primpart(const symbol &x, const ex &c) const
755 if (is_ex_exactly_of_type(*this, numeric))
759 if (is_ex_exactly_of_type(c, numeric))
760 return *this / (c * u);
762 return quo(*this, c * u, x, false);
767 * GCD of multivariate polynomials
770 /** Compute GCD of multivariate polynomials using the subresultant PRS
771 * algorithm. This function is used internally gy gcd().
773 * @param a first multivariate polynomial
774 * @param b second multivariate polynomial
775 * @param x pointer to symbol (main variable) in which to compute the GCD in
776 * @return the GCD as a new expression
779 static ex sr_gcd(const ex &a, const ex &b, const symbol *x)
781 // Sort c and d so that c has higher degree
783 int adeg = a.degree(*x), bdeg = b.degree(*x);
797 // Remove content from c and d, to be attached to GCD later
798 ex cont_c = c.content(*x);
799 ex cont_d = d.content(*x);
800 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
803 c = c.primpart(*x, cont_c);
804 d = d.primpart(*x, cont_d);
806 // First element of subresultant sequence
807 ex r = _ex0(), ri = _ex1(), psi = _ex1();
808 int delta = cdeg - ddeg;
811 // Calculate polynomial pseudo-remainder
812 r = prem(c, d, *x, false);
814 return gamma * d.primpart(*x);
817 if (!divide(r, ri * power(psi, delta), d, false))
818 throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
821 if (is_ex_exactly_of_type(r, numeric))
824 return gamma * r.primpart(*x);
827 // Next element of subresultant sequence
828 ri = c.expand().lcoeff(*x);
832 divide(power(ri, delta), power(psi, delta-1), psi, false);
838 /** Return maximum (absolute value) coefficient of a polynomial.
839 * This function is used internally by heur_gcd().
841 * @param e expanded multivariate polynomial
842 * @return maximum coefficient
845 numeric ex::max_coefficient(void) const
848 return bp->max_coefficient();
851 numeric basic::max_coefficient(void) const
856 numeric numeric::max_coefficient(void) const
861 numeric add::max_coefficient(void) const
863 epvector::const_iterator it = seq.begin();
864 epvector::const_iterator itend = seq.end();
865 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
866 numeric cur_max = abs(ex_to_numeric(overall_coeff));
867 while (it != itend) {
869 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
870 a = abs(ex_to_numeric(it->coeff));
878 numeric mul::max_coefficient(void) const
880 #ifdef DO_GINAC_ASSERT
881 epvector::const_iterator it = seq.begin();
882 epvector::const_iterator itend = seq.end();
883 while (it != itend) {
884 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
887 #endif // def DO_GINAC_ASSERT
888 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
889 return abs(ex_to_numeric(overall_coeff));
893 /** Apply symmetric modular homomorphism to a multivariate polynomial.
894 * This function is used internally by heur_gcd().
896 * @param e expanded multivariate polynomial
898 * @return mapped polynomial
901 ex ex::smod(const numeric &xi) const
907 ex basic::smod(const numeric &xi) const
912 ex numeric::smod(const numeric &xi) const
914 #ifndef NO_GINAC_NAMESPACE
915 return GiNaC::smod(*this, xi);
916 #else // ndef NO_GINAC_NAMESPACE
917 return ::smod(*this, xi);
918 #endif // ndef NO_GINAC_NAMESPACE
921 ex add::smod(const numeric &xi) const
924 newseq.reserve(seq.size()+1);
925 epvector::const_iterator it = seq.begin();
926 epvector::const_iterator itend = seq.end();
927 while (it != itend) {
928 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
929 #ifndef NO_GINAC_NAMESPACE
930 numeric coeff = GiNaC::smod(ex_to_numeric(it->coeff), xi);
931 #else // ndef NO_GINAC_NAMESPACE
932 numeric coeff = ::smod(ex_to_numeric(it->coeff), xi);
933 #endif // ndef NO_GINAC_NAMESPACE
934 if (!coeff.is_zero())
935 newseq.push_back(expair(it->rest, coeff));
938 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
939 #ifndef NO_GINAC_NAMESPACE
940 numeric coeff = GiNaC::smod(ex_to_numeric(overall_coeff), xi);
941 #else // ndef NO_GINAC_NAMESPACE
942 numeric coeff = ::smod(ex_to_numeric(overall_coeff), xi);
943 #endif // ndef NO_GINAC_NAMESPACE
944 return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
947 ex mul::smod(const numeric &xi) const
949 #ifdef DO_GINAC_ASSERT
950 epvector::const_iterator it = seq.begin();
951 epvector::const_iterator itend = seq.end();
952 while (it != itend) {
953 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
956 #endif // def DO_GINAC_ASSERT
957 mul * mulcopyp=new mul(*this);
958 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
959 #ifndef NO_GINAC_NAMESPACE
960 mulcopyp->overall_coeff = GiNaC::smod(ex_to_numeric(overall_coeff),xi);
961 #else // ndef NO_GINAC_NAMESPACE
962 mulcopyp->overall_coeff = ::smod(ex_to_numeric(overall_coeff),xi);
963 #endif // ndef NO_GINAC_NAMESPACE
964 mulcopyp->clearflag(status_flags::evaluated);
965 mulcopyp->clearflag(status_flags::hash_calculated);
966 return mulcopyp->setflag(status_flags::dynallocated);
970 /** Exception thrown by heur_gcd() to signal failure. */
971 class gcdheu_failed {};
973 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
974 * get_symbol_stats() must have been called previously with the input
975 * polynomials and an iterator to the first element of the sym_desc vector
976 * passed in. This function is used internally by gcd().
978 * @param a first multivariate polynomial (expanded)
979 * @param b second multivariate polynomial (expanded)
980 * @param ca cofactor of polynomial a (returned), NULL to suppress
981 * calculation of cofactor
982 * @param cb cofactor of polynomial b (returned), NULL to suppress
983 * calculation of cofactor
984 * @param var iterator to first element of vector of sym_desc structs
985 * @return the GCD as a new expression
987 * @exception gcdheu_failed() */
989 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
991 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
992 numeric g = gcd(ex_to_numeric(a), ex_to_numeric(b));
997 *ca = ex_to_numeric(a).mul(rg);
999 *cb = ex_to_numeric(b).mul(rg);
1003 // The first symbol is our main variable
1004 const symbol *x = var->sym;
1006 // Remove integer content
1007 numeric gc = gcd(a.integer_content(), b.integer_content());
1008 numeric rgc = gc.inverse();
1011 int maxdeg = max(p.degree(*x), q.degree(*x));
1013 // Find evaluation point
1014 numeric mp = p.max_coefficient(), mq = q.max_coefficient();
1017 xi = mq * _num2() + _num2();
1019 xi = mp * _num2() + _num2();
1022 for (int t=0; t<6; t++) {
1023 if (xi.int_length() * maxdeg > 50000)
1024 throw gcdheu_failed();
1026 // Apply evaluation homomorphism and calculate GCD
1027 ex gamma = heur_gcd(p.subs(*x == xi), q.subs(*x == xi), NULL, NULL, var+1).expand();
1028 if (!is_ex_exactly_of_type(gamma, fail)) {
1030 // Reconstruct polynomial from GCD of mapped polynomials
1032 numeric rxi = xi.inverse();
1033 for (int i=0; !gamma.is_zero(); i++) {
1034 ex gi = gamma.smod(xi);
1035 g += gi * power(*x, i);
1036 gamma = (gamma - gi) * rxi;
1038 // Remove integer content
1039 g /= g.integer_content();
1041 // If the calculated polynomial divides both a and b, this is the GCD
1043 if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1045 ex lc = g.lcoeff(*x);
1046 if (is_ex_exactly_of_type(lc, numeric) && lc.compare(_ex0()) < 0)
1053 // Next evaluation point
1054 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1056 return *new ex(fail());
1060 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1063 * @param a first multivariate polynomial
1064 * @param b second multivariate polynomial
1065 * @param check_args check whether a and b are polynomials with rational
1066 * coefficients (defaults to "true")
1067 * @return the GCD as a new expression */
1069 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1071 // Some trivial cases
1072 ex aex = a.expand(), bex = b.expand();
1073 if (aex.is_zero()) {
1080 if (bex.is_zero()) {
1087 if (aex.is_equal(_ex1()) || bex.is_equal(_ex1())) {
1095 if (a.is_equal(b)) {
1103 if (is_ex_exactly_of_type(aex, numeric) && is_ex_exactly_of_type(bex, numeric)) {
1104 numeric g = gcd(ex_to_numeric(aex), ex_to_numeric(bex));
1106 *ca = ex_to_numeric(aex) / g;
1108 *cb = ex_to_numeric(bex) / g;
1111 if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)) {
1112 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1115 // Gather symbol statistics
1116 sym_desc_vec sym_stats;
1117 get_symbol_stats(a, b, sym_stats);
1119 // The symbol with least degree is our main variable
1120 sym_desc_vec::const_iterator var = sym_stats.begin();
1121 const symbol *x = var->sym;
1123 // Cancel trivial common factor
1124 int ldeg_a = var->ldeg_a;
1125 int ldeg_b = var->ldeg_b;
1126 int min_ldeg = min(ldeg_a, ldeg_b);
1128 ex common = power(*x, min_ldeg);
1129 //clog << "trivial common factor " << common << endl;
1130 return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1133 // Try to eliminate variables
1134 if (var->deg_a == 0) {
1135 //clog << "eliminating variable " << *x << " from b" << endl;
1136 ex c = bex.content(*x);
1137 ex g = gcd(aex, c, ca, cb, false);
1139 *cb *= bex.unit(*x) * bex.primpart(*x, c);
1141 } else if (var->deg_b == 0) {
1142 //clog << "eliminating variable " << *x << " from a" << endl;
1143 ex c = aex.content(*x);
1144 ex g = gcd(c, bex, ca, cb, false);
1146 *ca *= aex.unit(*x) * aex.primpart(*x, c);
1150 // Try heuristic algorithm first, fall back to PRS if that failed
1153 g = heur_gcd(aex, bex, ca, cb, var);
1154 } catch (gcdheu_failed) {
1155 g = *new ex(fail());
1157 if (is_ex_exactly_of_type(g, fail)) {
1158 // clog << "heuristics failed" << endl;
1159 g = sr_gcd(aex, bex, x);
1161 divide(aex, g, *ca, false);
1163 divide(bex, g, *cb, false);
1169 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1171 * @param a first multivariate polynomial
1172 * @param b second multivariate polynomial
1173 * @param check_args check whether a and b are polynomials with rational
1174 * coefficients (defaults to "true")
1175 * @return the LCM as a new expression */
1176 ex lcm(const ex &a, const ex &b, bool check_args)
1178 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
1179 return gcd(ex_to_numeric(a), ex_to_numeric(b));
1180 if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1181 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1184 ex g = gcd(a, b, &ca, &cb, false);
1190 * Square-free factorization
1193 // Univariate GCD of polynomials in Q[x] (used internally by sqrfree()).
1194 // a and b can be multivariate polynomials but they are treated as univariate polynomials in x.
1195 static ex univariate_gcd(const ex &a, const ex &b, const symbol &x)
1201 if (a.is_equal(_ex1()) || b.is_equal(_ex1()))
1203 if (is_ex_of_type(a, numeric) && is_ex_of_type(b, numeric))
1204 return gcd(ex_to_numeric(a), ex_to_numeric(b));
1205 if (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1206 throw(std::invalid_argument("univariate_gcd: arguments must be polynomials over the rationals"));
1208 // Euclidean algorithm
1210 if (a.degree(x) >= b.degree(x)) {
1218 r = rem(c, d, x, false);
1224 return d / d.lcoeff(x);
1228 /** Compute square-free factorization of multivariate polynomial a(x) using
1231 * @param a multivariate polynomial
1232 * @param x variable to factor in
1233 * @return factored polynomial */
1234 ex sqrfree(const ex &a, const symbol &x)
1239 ex c = univariate_gcd(a, b, x);
1241 if (c.is_equal(_ex1())) {
1245 ex y = quo(b, c, x);
1246 ex z = y - w.diff(x);
1247 while (!z.is_zero()) {
1248 ex g = univariate_gcd(w, z, x);
1256 return res * power(w, i);
1261 * Normal form of rational functions
1264 // Create a symbol for replacing the expression "e" (or return a previously
1265 // assigned symbol). The symbol is appended to sym_list and returned, the
1266 // expression is appended to repl_list.
1267 static ex replace_with_symbol(const ex &e, lst &sym_lst, lst &repl_lst)
1269 // Expression already in repl_lst? Then return the assigned symbol
1270 for (int i=0; i<repl_lst.nops(); i++)
1271 if (repl_lst.op(i).is_equal(e))
1272 return sym_lst.op(i);
1274 // Otherwise create new symbol and add to list, taking care that the
1275 // replacement expression doesn't contain symbols from the sym_lst
1276 // because subs() is not recursive
1279 ex e_replaced = e.subs(sym_lst, repl_lst);
1281 repl_lst.append(e_replaced);
1286 /** Default implementation of ex::normal(). It replaces the object with a
1288 * @see ex::normal */
1289 ex basic::normal(lst &sym_lst, lst &repl_lst, int level) const
1291 return replace_with_symbol(*this, sym_lst, repl_lst);
1295 /** Implementation of ex::normal() for symbols. This returns the unmodifies symbol.
1296 * @see ex::normal */
1297 ex symbol::normal(lst &sym_lst, lst &repl_lst, int level) const
1303 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1304 * into re+I*im and replaces I and non-rational real numbers with a temporary
1306 * @see ex::normal */
1307 ex numeric::normal(lst &sym_lst, lst &repl_lst, int level) const
1313 return replace_with_symbol(*this, sym_lst, repl_lst);
1315 numeric re = real(), im = imag();
1316 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, sym_lst, repl_lst);
1317 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, sym_lst, repl_lst);
1318 return re_ex + im_ex * replace_with_symbol(I, sym_lst, repl_lst);
1324 * Helper function for fraction cancellation (returns cancelled fraction n/d)
1326 static ex frac_cancel(const ex &n, const ex &d)
1330 ex pre_factor = _ex1();
1332 // Handle special cases where numerator or denominator is 0
1335 if (den.expand().is_zero())
1336 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
1338 // More special cases
1339 if (is_ex_exactly_of_type(den, numeric))
1344 // Bring numerator and denominator to Z[X] by multiplying with
1345 // LCM of all coefficients' denominators
1346 ex num_lcm = lcm_of_coefficients_denominators(num);
1347 ex den_lcm = lcm_of_coefficients_denominators(den);
1350 pre_factor = den_lcm / num_lcm;
1352 // Cancel GCD from numerator and denominator
1354 if (gcd(num, den, &cnum, &cden, false) != _ex1()) {
1359 // Make denominator unit normal (i.e. coefficient of first symbol
1360 // as defined by get_first_symbol() is made positive)
1362 if (get_first_symbol(den, x)) {
1363 if (den.unit(*x).compare(_ex0()) < 0) {
1368 return pre_factor * num / den;
1372 /** Implementation of ex::normal() for a sum. It expands terms and performs
1373 * fractional addition.
1374 * @see ex::normal */
1375 ex add::normal(lst &sym_lst, lst &repl_lst, int level) const
1377 // Normalize and expand children
1379 o.reserve(seq.size()+1);
1380 epvector::const_iterator it = seq.begin(), itend = seq.end();
1381 while (it != itend) {
1382 ex n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1).expand();
1383 if (is_ex_exactly_of_type(n, add)) {
1384 epvector::const_iterator bit = (static_cast<add *>(n.bp))->seq.begin(), bitend = (static_cast<add *>(n.bp))->seq.end();
1385 while (bit != bitend) {
1386 o.push_back(recombine_pair_to_ex(*bit));
1389 o.push_back((static_cast<add *>(n.bp))->overall_coeff);
1394 o.push_back(overall_coeff.bp->normal(sym_lst, repl_lst, level-1));
1396 // Determine common denominator
1398 exvector::const_iterator ait = o.begin(), aitend = o.end();
1399 while (ait != aitend) {
1400 den = lcm((*ait).denom(false), den, false);
1405 if (den.is_equal(_ex1()))
1406 return (new add(o))->setflag(status_flags::dynallocated);
1409 for (ait=o.begin(); ait!=aitend; ait++) {
1411 if (!divide(den, (*ait).denom(false), q, false)) {
1412 // should not happen
1413 throw(std::runtime_error("invalid expression in add::normal, division failed"));
1415 num_seq.push_back((*ait).numer(false) * q);
1417 ex num = add(num_seq);
1419 // Cancel common factors from num/den
1420 return frac_cancel(num, den);
1425 /** Implementation of ex::normal() for a product. It cancels common factors
1427 * @see ex::normal() */
1428 ex mul::normal(lst &sym_lst, lst &repl_lst, int level) const
1430 // Normalize children
1432 o.reserve(seq.size()+1);
1433 epvector::const_iterator it = seq.begin(), itend = seq.end();
1434 while (it != itend) {
1435 o.push_back(recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1));
1438 o.push_back(overall_coeff.bp->normal(sym_lst, repl_lst, level-1));
1439 ex n = (new mul(o))->setflag(status_flags::dynallocated);
1440 return frac_cancel(n.numer(false), n.denom(false));
1444 /** Implementation of ex::normal() for powers. It normalizes the basis,
1445 * distributes integer exponents to numerator and denominator, and replaces
1446 * non-integer powers by temporary symbols.
1447 * @see ex::normal */
1448 ex power::normal(lst &sym_lst, lst &repl_lst, int level) const
1450 if (exponent.info(info_flags::integer)) {
1451 // Integer powers are distributed
1452 ex n = basis.bp->normal(sym_lst, repl_lst, level-1);
1453 ex num = n.numer(false);
1454 ex den = n.denom(false);
1455 return power(num, exponent) / power(den, exponent);
1457 // Non-integer powers are replaced by temporary symbol (after normalizing basis)
1458 ex n = power(basis.bp->normal(sym_lst, repl_lst, level-1), exponent);
1459 return replace_with_symbol(n, sym_lst, repl_lst);
1464 /** Implementation of ex::normal() for series. It normalizes each coefficient and
1465 * replaces the series by a temporary symbol.
1466 * @see ex::normal */
1467 ex series::normal(lst &sym_lst, lst &repl_lst, int level) const
1470 new_seq.reserve(seq.size());
1472 epvector::const_iterator it = seq.begin(), itend = seq.end();
1473 while (it != itend) {
1474 new_seq.push_back(expair(it->rest.normal(), it->coeff));
1478 ex n = series(var, point, new_seq);
1479 return replace_with_symbol(n, sym_lst, repl_lst);
1483 /** Normalization of rational functions.
1484 * This function converts an expression to its normal form
1485 * "numerator/denominator", where numerator and denominator are (relatively
1486 * prime) polynomials. Any subexpressions which are not rational functions
1487 * (like non-rational numbers, non-integer powers or functions like Sin(),
1488 * Cos() etc.) are replaced by temporary symbols which are re-substituted by
1489 * the (normalized) subexpressions before normal() returns (this way, any
1490 * expression can be treated as a rational function). normal() is applied
1491 * recursively to arguments of functions etc.
1493 * @param level maximum depth of recursion
1494 * @return normalized expression */
1495 ex ex::normal(int level) const
1497 lst sym_lst, repl_lst;
1498 ex e = bp->normal(sym_lst, repl_lst, level);
1499 if (sym_lst.nops() > 0)
1500 return e.subs(sym_lst, repl_lst);
1505 #ifndef NO_GINAC_NAMESPACE
1506 } // namespace GiNaC
1507 #endif // ndef NO_GINAC_NAMESPACE