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_NAMESPACE_GINAC
52 #endif // ndef NO_NAMESPACE_GINAC
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 numeric &lcm)
229 if (is_ex_exactly_of_type(e, mul)) {
231 numeric lcm_accum = _num1();
232 for (unsigned i=0; i<e.nops(); i++) {
233 numeric op_lcm = lcmcoeff(e.op(i), _num1());
234 c *= multiply_lcm(e.op(i), op_lcm);
237 c *= lcm / lcm_accum;
239 } else if (is_ex_exactly_of_type(e, add)) {
241 for (unsigned i=0; i<e.nops(); i++)
242 c += multiply_lcm(e.op(i), lcm);
244 } else if (is_ex_exactly_of_type(e, power)) {
245 return pow(multiply_lcm(e.op(0), lcm.power(ex_to_numeric(e.op(1)).inverse())), e.op(1));
251 /** Compute the integer content (= GCD of all numeric coefficients) of an
252 * expanded polynomial.
254 * @param e expanded polynomial
255 * @return integer content */
257 numeric ex::integer_content(void) const
260 return bp->integer_content();
263 numeric basic::integer_content(void) const
268 numeric numeric::integer_content(void) const
273 numeric add::integer_content(void) const
275 epvector::const_iterator it = seq.begin();
276 epvector::const_iterator itend = seq.end();
278 while (it != itend) {
279 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
280 GINAC_ASSERT(is_ex_exactly_of_type(it->coeff,numeric));
281 c = gcd(ex_to_numeric(it->coeff), c);
284 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
285 c = gcd(ex_to_numeric(overall_coeff),c);
289 numeric mul::integer_content(void) const
291 #ifdef DO_GINAC_ASSERT
292 epvector::const_iterator it = seq.begin();
293 epvector::const_iterator itend = seq.end();
294 while (it != itend) {
295 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
298 #endif // def DO_GINAC_ASSERT
299 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
300 return abs(ex_to_numeric(overall_coeff));
305 * Polynomial quotients and remainders
308 /** Quotient q(x) of polynomials a(x) and b(x) in Q[x].
309 * It satisfies a(x)=b(x)*q(x)+r(x).
311 * @param a first polynomial in x (dividend)
312 * @param b second polynomial in x (divisor)
313 * @param x a and b are polynomials in x
314 * @param check_args check whether a and b are polynomials with rational
315 * coefficients (defaults to "true")
316 * @return quotient of a and b in Q[x] */
318 ex quo(const ex &a, const ex &b, const symbol &x, bool check_args)
321 throw(std::overflow_error("quo: division by zero"));
322 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
328 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
329 throw(std::invalid_argument("quo: arguments must be polynomials over the rationals"));
331 // Polynomial long division
336 int bdeg = b.degree(x);
337 int rdeg = r.degree(x);
338 ex blcoeff = b.expand().coeff(x, bdeg);
339 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
340 while (rdeg >= bdeg) {
341 ex term, rcoeff = r.coeff(x, rdeg);
342 if (blcoeff_is_numeric)
343 term = rcoeff / blcoeff;
345 if (!divide(rcoeff, blcoeff, term, false))
346 return *new ex(fail());
348 term *= power(x, rdeg - bdeg);
350 r -= (term * b).expand();
359 /** Remainder r(x) of polynomials a(x) and b(x) in Q[x].
360 * It satisfies a(x)=b(x)*q(x)+r(x).
362 * @param a first polynomial in x (dividend)
363 * @param b second polynomial in x (divisor)
364 * @param x a and b are polynomials in x
365 * @param check_args check whether a and b are polynomials with rational
366 * coefficients (defaults to "true")
367 * @return remainder of a(x) and b(x) in Q[x] */
369 ex rem(const ex &a, const ex &b, const symbol &x, bool check_args)
372 throw(std::overflow_error("rem: division by zero"));
373 if (is_ex_exactly_of_type(a, numeric)) {
374 if (is_ex_exactly_of_type(b, numeric))
383 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
384 throw(std::invalid_argument("rem: arguments must be polynomials over the rationals"));
386 // Polynomial long division
390 int bdeg = b.degree(x);
391 int rdeg = r.degree(x);
392 ex blcoeff = b.expand().coeff(x, bdeg);
393 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
394 while (rdeg >= bdeg) {
395 ex term, rcoeff = r.coeff(x, rdeg);
396 if (blcoeff_is_numeric)
397 term = rcoeff / blcoeff;
399 if (!divide(rcoeff, blcoeff, term, false))
400 return *new ex(fail());
402 term *= power(x, rdeg - bdeg);
403 r -= (term * b).expand();
412 /** Pseudo-remainder of polynomials a(x) and b(x) in Z[x].
414 * @param a first polynomial in x (dividend)
415 * @param b second polynomial in x (divisor)
416 * @param x a and b are polynomials in x
417 * @param check_args check whether a and b are polynomials with rational
418 * coefficients (defaults to "true")
419 * @return pseudo-remainder of a(x) and b(x) in Z[x] */
421 ex prem(const ex &a, const ex &b, const symbol &x, bool check_args)
424 throw(std::overflow_error("prem: division by zero"));
425 if (is_ex_exactly_of_type(a, numeric)) {
426 if (is_ex_exactly_of_type(b, numeric))
431 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
432 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
434 // Polynomial long division
437 int rdeg = r.degree(x);
438 int bdeg = eb.degree(x);
441 blcoeff = eb.coeff(x, bdeg);
445 eb -= blcoeff * power(x, bdeg);
449 int delta = rdeg - bdeg + 1, i = 0;
450 while (rdeg >= bdeg && !r.is_zero()) {
451 ex rlcoeff = r.coeff(x, rdeg);
452 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
456 r -= rlcoeff * power(x, rdeg);
457 r = (blcoeff * r).expand() - term;
461 return power(blcoeff, delta - i) * r;
465 /** Exact polynomial division of a(X) by b(X) in Q[X].
467 * @param a first multivariate polynomial (dividend)
468 * @param b second multivariate polynomial (divisor)
469 * @param q quotient (returned)
470 * @param check_args check whether a and b are polynomials with rational
471 * coefficients (defaults to "true")
472 * @return "true" when exact division succeeds (quotient returned in q),
473 * "false" otherwise */
475 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
479 throw(std::overflow_error("divide: division by zero"));
480 if (is_ex_exactly_of_type(b, numeric)) {
483 } else if (is_ex_exactly_of_type(a, numeric))
491 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
492 throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
496 if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
497 throw(std::invalid_argument("invalid expression in divide()"));
499 // Polynomial long division (recursive)
503 int bdeg = b.degree(*x);
504 int rdeg = r.degree(*x);
505 ex blcoeff = b.expand().coeff(*x, bdeg);
506 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
507 while (rdeg >= bdeg) {
508 ex term, rcoeff = r.coeff(*x, rdeg);
509 if (blcoeff_is_numeric)
510 term = rcoeff / blcoeff;
512 if (!divide(rcoeff, blcoeff, term, false))
514 term *= power(*x, rdeg - bdeg);
516 r -= (term * b).expand();
530 typedef pair<ex, ex> ex2;
531 typedef pair<ex, bool> exbool;
534 bool operator() (const ex2 p, const ex2 q) const
536 return p.first.compare(q.first) < 0 || (!(q.first.compare(p.first) < 0) && p.second.compare(q.second) < 0);
540 typedef map<ex2, exbool, ex2_less> ex2_exbool_remember;
544 /** Exact polynomial division of a(X) by b(X) in Z[X].
545 * This functions works like divide() but the input and output polynomials are
546 * in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
547 * divide(), it doesnĀ“t check whether the input polynomials really are integer
548 * polynomials, so be careful of what you pass in. Also, you have to run
549 * get_symbol_stats() over the input polynomials before calling this function
550 * and pass an iterator to the first element of the sym_desc vector. This
551 * function is used internally by the heur_gcd().
553 * @param a first multivariate polynomial (dividend)
554 * @param b second multivariate polynomial (divisor)
555 * @param q quotient (returned)
556 * @param var iterator to first element of vector of sym_desc structs
557 * @return "true" when exact division succeeds (the quotient is returned in
558 * q), "false" otherwise.
559 * @see get_symbol_stats, heur_gcd */
560 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
564 throw(std::overflow_error("divide_in_z: division by zero"));
565 if (b.is_equal(_ex1())) {
569 if (is_ex_exactly_of_type(a, numeric)) {
570 if (is_ex_exactly_of_type(b, numeric)) {
572 return q.info(info_flags::integer);
585 static ex2_exbool_remember dr_remember;
586 ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
587 if (remembered != dr_remember.end()) {
588 q = remembered->second.first;
589 return remembered->second.second;
594 const symbol *x = var->sym;
597 int adeg = a.degree(*x), bdeg = b.degree(*x);
603 // Polynomial long division (recursive)
609 ex blcoeff = eb.coeff(*x, bdeg);
610 while (rdeg >= bdeg) {
611 ex term, rcoeff = r.coeff(*x, rdeg);
612 if (!divide_in_z(rcoeff, blcoeff, term, var+1))
614 term = (term * power(*x, rdeg - bdeg)).expand();
616 r -= (term * eb).expand();
619 dr_remember[ex2(a, b)] = exbool(q, true);
626 dr_remember[ex2(a, b)] = exbool(q, false);
632 // Trial division using polynomial interpolation
635 // Compute values at evaluation points 0..adeg
636 vector<numeric> alpha; alpha.reserve(adeg + 1);
637 exvector u; u.reserve(adeg + 1);
638 numeric point = _num0();
640 for (i=0; i<=adeg; i++) {
641 ex bs = b.subs(*x == point);
642 while (bs.is_zero()) {
644 bs = b.subs(*x == point);
646 if (!divide_in_z(a.subs(*x == point), bs, c, var+1))
648 alpha.push_back(point);
654 vector<numeric> rcp; rcp.reserve(adeg + 1);
656 for (k=1; k<=adeg; k++) {
657 numeric product = alpha[k] - alpha[0];
659 product *= alpha[k] - alpha[i];
660 rcp.push_back(product.inverse());
663 // Compute Newton coefficients
664 exvector v; v.reserve(adeg + 1);
666 for (k=1; k<=adeg; k++) {
668 for (i=k-2; i>=0; i--)
669 temp = temp * (alpha[k] - alpha[i]) + v[i];
670 v.push_back((u[k] - temp) * rcp[k]);
673 // Convert from Newton form to standard form
675 for (k=adeg-1; k>=0; k--)
676 c = c * (*x - alpha[k]) + v[k];
678 if (c.degree(*x) == (adeg - bdeg)) {
688 * Separation of unit part, content part and primitive part of polynomials
691 /** Compute unit part (= sign of leading coefficient) of a multivariate
692 * polynomial in Z[x]. The product of unit part, content part, and primitive
693 * part is the polynomial itself.
695 * @param x variable in which to compute the unit part
697 * @see ex::content, ex::primpart */
698 ex ex::unit(const symbol &x) const
700 ex c = expand().lcoeff(x);
701 if (is_ex_exactly_of_type(c, numeric))
702 return c < _ex0() ? _ex_1() : _ex1();
705 if (get_first_symbol(c, y))
708 throw(std::invalid_argument("invalid expression in unit()"));
713 /** Compute content part (= unit normal GCD of all coefficients) of a
714 * multivariate polynomial in Z[x]. The product of unit part, content part,
715 * and primitive part is the polynomial itself.
717 * @param x variable in which to compute the content part
718 * @return content part
719 * @see ex::unit, ex::primpart */
720 ex ex::content(const symbol &x) const
724 if (is_ex_exactly_of_type(*this, numeric))
725 return info(info_flags::negative) ? -*this : *this;
730 // First, try the integer content
731 ex c = e.integer_content();
733 ex lcoeff = r.lcoeff(x);
734 if (lcoeff.info(info_flags::integer))
737 // GCD of all coefficients
738 int deg = e.degree(x);
739 int ldeg = e.ldegree(x);
741 return e.lcoeff(x) / e.unit(x);
743 for (int i=ldeg; i<=deg; i++)
744 c = gcd(e.coeff(x, i), c, NULL, NULL, false);
749 /** Compute primitive part of a multivariate polynomial in Z[x].
750 * The product of unit part, content part, and primitive part is the
753 * @param x variable in which to compute the primitive part
754 * @return primitive part
755 * @see ex::unit, ex::content */
756 ex ex::primpart(const symbol &x) const
760 if (is_ex_exactly_of_type(*this, numeric))
767 if (is_ex_exactly_of_type(c, numeric))
768 return *this / (c * u);
770 return quo(*this, c * u, x, false);
774 /** Compute primitive part of a multivariate polynomial in Z[x] when the
775 * content part is already known. This function is faster in computing the
776 * primitive part than the previous function.
778 * @param x variable in which to compute the primitive part
779 * @param c previously computed content part
780 * @return primitive part */
782 ex ex::primpart(const symbol &x, const ex &c) const
788 if (is_ex_exactly_of_type(*this, numeric))
792 if (is_ex_exactly_of_type(c, numeric))
793 return *this / (c * u);
795 return quo(*this, c * u, x, false);
800 * GCD of multivariate polynomials
803 /** Compute GCD of multivariate polynomials using the subresultant PRS
804 * algorithm. This function is used internally gy gcd().
806 * @param a first multivariate polynomial
807 * @param b second multivariate polynomial
808 * @param x pointer to symbol (main variable) in which to compute the GCD in
809 * @return the GCD as a new expression
812 static ex sr_gcd(const ex &a, const ex &b, const symbol *x)
814 //clog << "sr_gcd(" << a << "," << b << ")\n";
816 // Sort c and d so that c has higher degree
818 int adeg = a.degree(*x), bdeg = b.degree(*x);
832 // Remove content from c and d, to be attached to GCD later
833 ex cont_c = c.content(*x);
834 ex cont_d = d.content(*x);
835 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
838 c = c.primpart(*x, cont_c);
839 d = d.primpart(*x, cont_d);
841 // First element of subresultant sequence
842 ex r = _ex0(), ri = _ex1(), psi = _ex1();
843 int delta = cdeg - ddeg;
846 // Calculate polynomial pseudo-remainder
847 r = prem(c, d, *x, false);
849 return gamma * d.primpart(*x);
852 if (!divide(r, ri * power(psi, delta), d, false))
853 throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
856 if (is_ex_exactly_of_type(r, numeric))
859 return gamma * r.primpart(*x);
862 // Next element of subresultant sequence
863 ri = c.expand().lcoeff(*x);
867 divide(power(ri, delta), power(psi, delta-1), psi, false);
873 /** Return maximum (absolute value) coefficient of a polynomial.
874 * This function is used internally by heur_gcd().
876 * @param e expanded multivariate polynomial
877 * @return maximum coefficient
880 numeric ex::max_coefficient(void) const
883 return bp->max_coefficient();
886 numeric basic::max_coefficient(void) const
891 numeric numeric::max_coefficient(void) const
896 numeric add::max_coefficient(void) const
898 epvector::const_iterator it = seq.begin();
899 epvector::const_iterator itend = seq.end();
900 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
901 numeric cur_max = abs(ex_to_numeric(overall_coeff));
902 while (it != itend) {
904 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
905 a = abs(ex_to_numeric(it->coeff));
913 numeric mul::max_coefficient(void) const
915 #ifdef DO_GINAC_ASSERT
916 epvector::const_iterator it = seq.begin();
917 epvector::const_iterator itend = seq.end();
918 while (it != itend) {
919 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
922 #endif // def DO_GINAC_ASSERT
923 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
924 return abs(ex_to_numeric(overall_coeff));
928 /** Apply symmetric modular homomorphism to a multivariate polynomial.
929 * This function is used internally by heur_gcd().
931 * @param e expanded multivariate polynomial
933 * @return mapped polynomial
936 ex ex::smod(const numeric &xi) const
942 ex basic::smod(const numeric &xi) const
947 ex numeric::smod(const numeric &xi) const
949 #ifndef NO_NAMESPACE_GINAC
950 return GiNaC::smod(*this, xi);
951 #else // ndef NO_NAMESPACE_GINAC
952 return ::smod(*this, xi);
953 #endif // ndef NO_NAMESPACE_GINAC
956 ex add::smod(const numeric &xi) const
959 newseq.reserve(seq.size()+1);
960 epvector::const_iterator it = seq.begin();
961 epvector::const_iterator itend = seq.end();
962 while (it != itend) {
963 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
964 #ifndef NO_NAMESPACE_GINAC
965 numeric coeff = GiNaC::smod(ex_to_numeric(it->coeff), xi);
966 #else // ndef NO_NAMESPACE_GINAC
967 numeric coeff = ::smod(ex_to_numeric(it->coeff), xi);
968 #endif // ndef NO_NAMESPACE_GINAC
969 if (!coeff.is_zero())
970 newseq.push_back(expair(it->rest, coeff));
973 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
974 #ifndef NO_NAMESPACE_GINAC
975 numeric coeff = GiNaC::smod(ex_to_numeric(overall_coeff), xi);
976 #else // ndef NO_NAMESPACE_GINAC
977 numeric coeff = ::smod(ex_to_numeric(overall_coeff), xi);
978 #endif // ndef NO_NAMESPACE_GINAC
979 return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
982 ex mul::smod(const numeric &xi) const
984 #ifdef DO_GINAC_ASSERT
985 epvector::const_iterator it = seq.begin();
986 epvector::const_iterator itend = seq.end();
987 while (it != itend) {
988 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
991 #endif // def DO_GINAC_ASSERT
992 mul * mulcopyp=new mul(*this);
993 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
994 #ifndef NO_NAMESPACE_GINAC
995 mulcopyp->overall_coeff = GiNaC::smod(ex_to_numeric(overall_coeff),xi);
996 #else // ndef NO_NAMESPACE_GINAC
997 mulcopyp->overall_coeff = ::smod(ex_to_numeric(overall_coeff),xi);
998 #endif // ndef NO_NAMESPACE_GINAC
999 mulcopyp->clearflag(status_flags::evaluated);
1000 mulcopyp->clearflag(status_flags::hash_calculated);
1001 return mulcopyp->setflag(status_flags::dynallocated);
1005 /** Exception thrown by heur_gcd() to signal failure. */
1006 class gcdheu_failed {};
1008 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1009 * get_symbol_stats() must have been called previously with the input
1010 * polynomials and an iterator to the first element of the sym_desc vector
1011 * passed in. This function is used internally by gcd().
1013 * @param a first multivariate polynomial (expanded)
1014 * @param b second multivariate polynomial (expanded)
1015 * @param ca cofactor of polynomial a (returned), NULL to suppress
1016 * calculation of cofactor
1017 * @param cb cofactor of polynomial b (returned), NULL to suppress
1018 * calculation of cofactor
1019 * @param var iterator to first element of vector of sym_desc structs
1020 * @return the GCD as a new expression
1022 * @exception gcdheu_failed() */
1024 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
1026 //clog << "heur_gcd(" << a << "," << b << ")\n";
1028 // GCD of two numeric values -> CLN
1029 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1030 numeric g = gcd(ex_to_numeric(a), ex_to_numeric(b));
1035 *ca = ex_to_numeric(a).mul(rg);
1037 *cb = ex_to_numeric(b).mul(rg);
1041 // The first symbol is our main variable
1042 const symbol *x = var->sym;
1044 // Remove integer content
1045 numeric gc = gcd(a.integer_content(), b.integer_content());
1046 numeric rgc = gc.inverse();
1049 int maxdeg = max(p.degree(*x), q.degree(*x));
1051 // Find evaluation point
1052 numeric mp = p.max_coefficient(), mq = q.max_coefficient();
1055 xi = mq * _num2() + _num2();
1057 xi = mp * _num2() + _num2();
1060 for (int t=0; t<6; t++) { // MAGIC
1061 if (xi.int_length() * maxdeg > 100000) { // MAGIC
1062 // clog << "giving up heur_gcd, xi.int_length = " << xi.int_length() << ", maxdeg = " << maxdeg << endl;
1063 throw gcdheu_failed();
1066 // Apply evaluation homomorphism and calculate GCD
1067 ex gamma = heur_gcd(p.subs(*x == xi), q.subs(*x == xi), NULL, NULL, var+1).expand();
1068 if (!is_ex_exactly_of_type(gamma, fail)) {
1070 // Reconstruct polynomial from GCD of mapped polynomials
1072 numeric rxi = xi.inverse();
1073 for (int i=0; !gamma.is_zero(); i++) {
1074 ex gi = gamma.smod(xi);
1075 g += gi * power(*x, i);
1076 gamma = (gamma - gi) * rxi;
1078 // Remove integer content
1079 g /= g.integer_content();
1081 // If the calculated polynomial divides both a and b, this is the GCD
1083 if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1085 ex lc = g.lcoeff(*x);
1086 if (is_ex_exactly_of_type(lc, numeric) && ex_to_numeric(lc).is_negative())
1093 // Next evaluation point
1094 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1096 return *new ex(fail());
1100 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1103 * @param a first multivariate polynomial
1104 * @param b second multivariate polynomial
1105 * @param check_args check whether a and b are polynomials with rational
1106 * coefficients (defaults to "true")
1107 * @return the GCD as a new expression */
1109 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1111 //clog << "gcd(" << a << "," << b << ")\n";
1113 // Partially factored cases (to avoid expanding large expressions)
1114 if (is_ex_exactly_of_type(a, mul)) {
1115 if (is_ex_exactly_of_type(b, mul) && b.nops() > a.nops())
1121 for (unsigned i=0; i<a.nops(); i++) {
1122 ex part_ca, part_cb;
1123 g *= gcd(a.op(i), part_b, &part_ca, &part_cb, check_args);
1132 } else if (is_ex_exactly_of_type(b, mul)) {
1133 if (is_ex_exactly_of_type(a, mul) && a.nops() > b.nops())
1139 for (unsigned i=0; i<b.nops(); i++) {
1140 ex part_ca, part_cb;
1141 g *= gcd(part_a, b.op(i), &part_ca, &part_cb, check_args);
1152 // Some trivial cases
1153 ex aex = a.expand(), bex = b.expand();
1154 if (aex.is_zero()) {
1161 if (bex.is_zero()) {
1168 if (aex.is_equal(_ex1()) || bex.is_equal(_ex1())) {
1176 if (a.is_equal(b)) {
1184 if (is_ex_exactly_of_type(aex, numeric) && is_ex_exactly_of_type(bex, numeric)) {
1185 numeric g = gcd(ex_to_numeric(aex), ex_to_numeric(bex));
1187 *ca = ex_to_numeric(aex) / g;
1189 *cb = ex_to_numeric(bex) / g;
1192 if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)) {
1193 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1196 // Gather symbol statistics
1197 sym_desc_vec sym_stats;
1198 get_symbol_stats(a, b, sym_stats);
1200 // The symbol with least degree is our main variable
1201 sym_desc_vec::const_iterator var = sym_stats.begin();
1202 const symbol *x = var->sym;
1204 // Cancel trivial common factor
1205 int ldeg_a = var->ldeg_a;
1206 int ldeg_b = var->ldeg_b;
1207 int min_ldeg = min(ldeg_a, ldeg_b);
1209 ex common = power(*x, min_ldeg);
1210 //clog << "trivial common factor " << common << endl;
1211 return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1214 // Try to eliminate variables
1215 if (var->deg_a == 0) {
1216 //clog << "eliminating variable " << *x << " from b" << endl;
1217 ex c = bex.content(*x);
1218 ex g = gcd(aex, c, ca, cb, false);
1220 *cb *= bex.unit(*x) * bex.primpart(*x, c);
1222 } else if (var->deg_b == 0) {
1223 //clog << "eliminating variable " << *x << " from a" << endl;
1224 ex c = aex.content(*x);
1225 ex g = gcd(c, bex, ca, cb, false);
1227 *ca *= aex.unit(*x) * aex.primpart(*x, c);
1231 // Try heuristic algorithm first, fall back to PRS if that failed
1234 g = heur_gcd(aex, bex, ca, cb, var);
1235 } catch (gcdheu_failed) {
1236 g = *new ex(fail());
1238 if (is_ex_exactly_of_type(g, fail)) {
1239 //clog << "heuristics failed" << endl;
1240 g = sr_gcd(aex, bex, x);
1242 divide(aex, g, *ca, false);
1244 divide(bex, g, *cb, false);
1250 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1252 * @param a first multivariate polynomial
1253 * @param b second multivariate polynomial
1254 * @param check_args check whether a and b are polynomials with rational
1255 * coefficients (defaults to "true")
1256 * @return the LCM as a new expression */
1257 ex lcm(const ex &a, const ex &b, bool check_args)
1259 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
1260 return lcm(ex_to_numeric(a), ex_to_numeric(b));
1261 if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1262 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1265 ex g = gcd(a, b, &ca, &cb, false);
1271 * Square-free factorization
1274 // Univariate GCD of polynomials in Q[x] (used internally by sqrfree()).
1275 // a and b can be multivariate polynomials but they are treated as univariate polynomials in x.
1276 static ex univariate_gcd(const ex &a, const ex &b, const symbol &x)
1282 if (a.is_equal(_ex1()) || b.is_equal(_ex1()))
1284 if (is_ex_of_type(a, numeric) && is_ex_of_type(b, numeric))
1285 return gcd(ex_to_numeric(a), ex_to_numeric(b));
1286 if (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1287 throw(std::invalid_argument("univariate_gcd: arguments must be polynomials over the rationals"));
1289 // Euclidean algorithm
1291 if (a.degree(x) >= b.degree(x)) {
1299 r = rem(c, d, x, false);
1305 return d / d.lcoeff(x);
1309 /** Compute square-free factorization of multivariate polynomial a(x) using
1312 * @param a multivariate polynomial
1313 * @param x variable to factor in
1314 * @return factored polynomial */
1315 ex sqrfree(const ex &a, const symbol &x)
1320 ex c = univariate_gcd(a, b, x);
1322 if (c.is_equal(_ex1())) {
1326 ex y = quo(b, c, x);
1327 ex z = y - w.diff(x);
1328 while (!z.is_zero()) {
1329 ex g = univariate_gcd(w, z, x);
1337 return res * power(w, i);
1342 * Normal form of rational functions
1346 * Note: The internal normal() functions (= basic::normal() and overloaded
1347 * functions) all return lists of the form {numerator, denominator}. This
1348 * is to get around mul::eval()'s automatic expansion of numeric coefficients.
1349 * E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
1350 * the information that (a+b) is the numerator and 3 is the denominator.
1353 /** Create a symbol for replacing the expression "e" (or return a previously
1354 * assigned symbol). The symbol is appended to sym_list and returned, the
1355 * expression is appended to repl_list.
1356 * @see ex::normal */
1357 static ex replace_with_symbol(const ex &e, lst &sym_lst, lst &repl_lst)
1359 // Expression already in repl_lst? Then return the assigned symbol
1360 for (unsigned i=0; i<repl_lst.nops(); i++)
1361 if (repl_lst.op(i).is_equal(e))
1362 return sym_lst.op(i);
1364 // Otherwise create new symbol and add to list, taking care that the
1365 // replacement expression doesn't contain symbols from the sym_lst
1366 // because subs() is not recursive
1369 ex e_replaced = e.subs(sym_lst, repl_lst);
1371 repl_lst.append(e_replaced);
1376 /** Default implementation of ex::normal(). It replaces the object with a
1378 * @see ex::normal */
1379 ex basic::normal(lst &sym_lst, lst &repl_lst, int level) const
1381 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1385 /** Implementation of ex::normal() for symbols. This returns the unmodified symbol.
1386 * @see ex::normal */
1387 ex symbol::normal(lst &sym_lst, lst &repl_lst, int level) const
1389 return (new lst(*this, _ex1()))->setflag(status_flags::dynallocated);
1393 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1394 * into re+I*im and replaces I and non-rational real numbers with a temporary
1396 * @see ex::normal */
1397 ex numeric::normal(lst &sym_lst, lst &repl_lst, int level) const
1399 numeric num = numer();
1402 if (num.is_real()) {
1403 if (!num.is_integer())
1404 numex = replace_with_symbol(numex, sym_lst, repl_lst);
1406 numeric re = num.real(), im = num.imag();
1407 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, sym_lst, repl_lst);
1408 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, sym_lst, repl_lst);
1409 numex = re_ex + im_ex * replace_with_symbol(I, sym_lst, repl_lst);
1412 // Denominator is always a real integer (see numeric::denom())
1413 return (new lst(numex, denom()))->setflag(status_flags::dynallocated);
1417 /** Fraction cancellation.
1418 * @param n numerator
1419 * @param d denominator
1420 * @return cancelled fraction {n, d} as a list */
1421 static ex frac_cancel(const ex &n, const ex &d)
1425 numeric pre_factor = _num1();
1427 //clog << "frac_cancel num = " << num << ", den = " << den << endl;
1429 // Handle special cases where numerator or denominator is 0
1431 return (new lst(_ex0(), _ex1()))->setflag(status_flags::dynallocated);
1432 if (den.expand().is_zero())
1433 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
1435 // Bring numerator and denominator to Z[X] by multiplying with
1436 // LCM of all coefficients' denominators
1437 numeric num_lcm = lcm_of_coefficients_denominators(num);
1438 numeric den_lcm = lcm_of_coefficients_denominators(den);
1439 num = multiply_lcm(num, num_lcm);
1440 den = multiply_lcm(den, den_lcm);
1441 pre_factor = den_lcm / num_lcm;
1443 // Cancel GCD from numerator and denominator
1445 if (gcd(num, den, &cnum, &cden, false) != _ex1()) {
1450 // Make denominator unit normal (i.e. coefficient of first symbol
1451 // as defined by get_first_symbol() is made positive)
1453 if (get_first_symbol(den, x)) {
1454 GINAC_ASSERT(is_ex_exactly_of_type(den.unit(*x),numeric));
1455 if (ex_to_numeric(den.unit(*x)).is_negative()) {
1461 // Return result as list
1462 //clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << endl;
1463 return (new lst(num * pre_factor.numer(), den * pre_factor.denom()))->setflag(status_flags::dynallocated);
1467 /** Implementation of ex::normal() for a sum. It expands terms and performs
1468 * fractional addition.
1469 * @see ex::normal */
1470 ex add::normal(lst &sym_lst, lst &repl_lst, int level) const
1472 // Normalize and expand children, chop into summands
1474 o.reserve(seq.size()+1);
1475 epvector::const_iterator it = seq.begin(), itend = seq.end();
1476 while (it != itend) {
1478 // Normalize and expand child
1479 ex n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1).expand();
1481 // If numerator is a sum, chop into summands
1482 if (is_ex_exactly_of_type(n.op(0), add)) {
1483 epvector::const_iterator bit = ex_to_add(n.op(0)).seq.begin(), bitend = ex_to_add(n.op(0)).seq.end();
1484 while (bit != bitend) {
1485 o.push_back((new lst(recombine_pair_to_ex(*bit), n.op(1)))->setflag(status_flags::dynallocated));
1489 // The overall_coeff is already normalized (== rational), we just
1490 // split it into numerator and denominator
1491 GINAC_ASSERT(ex_to_numeric(ex_to_add(n.op(0)).overall_coeff).is_rational());
1492 numeric overall = ex_to_numeric(ex_to_add(n.op(0)).overall_coeff);
1493 o.push_back((new lst(overall.numer(), overall.denom() * n.op(1)))->setflag(status_flags::dynallocated));
1498 o.push_back(overall_coeff.bp->normal(sym_lst, repl_lst, level-1));
1500 // o is now a vector of {numerator, denominator} lists
1502 // Determine common denominator
1504 exvector::const_iterator ait = o.begin(), aitend = o.end();
1505 //clog << "add::normal uses the following summands:\n";
1506 while (ait != aitend) {
1507 //clog << " num = " << ait->op(0) << ", den = " << ait->op(1) << endl;
1508 den = lcm(ait->op(1), den, false);
1511 //clog << " common denominator = " << den << endl;
1514 if (den.is_equal(_ex1())) {
1516 // Common denominator is 1, simply add all numerators
1518 for (ait=o.begin(); ait!=aitend; ait++) {
1519 num_seq.push_back(ait->op(0));
1521 return (new lst((new add(num_seq))->setflag(status_flags::dynallocated), den))->setflag(status_flags::dynallocated);
1525 // Perform fractional addition
1527 for (ait=o.begin(); ait!=aitend; ait++) {
1529 if (!divide(den, ait->op(1), q, false)) {
1530 // should not happen
1531 throw(std::runtime_error("invalid expression in add::normal, division failed"));
1533 num_seq.push_back((ait->op(0) * q).expand());
1535 ex num = (new add(num_seq))->setflag(status_flags::dynallocated);
1537 // Cancel common factors from num/den
1538 return frac_cancel(num, den);
1543 /** Implementation of ex::normal() for a product. It cancels common factors
1545 * @see ex::normal() */
1546 ex mul::normal(lst &sym_lst, lst &repl_lst, int level) const
1548 // Normalize children, separate into numerator and denominator
1552 epvector::const_iterator it = seq.begin(), itend = seq.end();
1553 while (it != itend) {
1554 n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1);
1559 n = overall_coeff.bp->normal(sym_lst, repl_lst, level-1);
1563 // Perform fraction cancellation
1564 return frac_cancel(num, den);
1568 /** Implementation of ex::normal() for powers. It normalizes the basis,
1569 * distributes integer exponents to numerator and denominator, and replaces
1570 * non-integer powers by temporary symbols.
1571 * @see ex::normal */
1572 ex power::normal(lst &sym_lst, lst &repl_lst, int level) const
1575 ex n = basis.bp->normal(sym_lst, repl_lst, level-1);
1577 if (exponent.info(info_flags::integer)) {
1579 if (exponent.info(info_flags::positive)) {
1581 // (a/b)^n -> {a^n, b^n}
1582 return (new lst(power(n.op(0), exponent), power(n.op(1), exponent)))->setflag(status_flags::dynallocated);
1584 } else if (exponent.info(info_flags::negative)) {
1586 // (a/b)^-n -> {b^n, a^n}
1587 return (new lst(power(n.op(1), -exponent), power(n.op(0), -exponent)))->setflag(status_flags::dynallocated);
1592 if (exponent.info(info_flags::positive)) {
1594 // (a/b)^x -> {sym((a/b)^x), 1}
1595 return (new lst(replace_with_symbol(power(n.op(0) / n.op(1), exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1597 } else if (exponent.info(info_flags::negative)) {
1599 if (n.op(1).is_equal(_ex1())) {
1601 // a^-x -> {1, sym(a^x)}
1602 return (new lst(_ex1(), replace_with_symbol(power(n.op(0), -exponent), sym_lst, repl_lst)))->setflag(status_flags::dynallocated);
1606 // (a/b)^-x -> {sym((b/a)^x), 1}
1607 return (new lst(replace_with_symbol(power(n.op(1) / n.op(0), -exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1610 } else { // exponent not numeric
1612 // (a/b)^x -> {sym((a/b)^x, 1}
1613 return (new lst(replace_with_symbol(power(n.op(0) / n.op(1), exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1619 /** Implementation of ex::normal() for pseries. It normalizes each coefficient and
1620 * replaces the series by a temporary symbol.
1621 * @see ex::normal */
1622 ex pseries::normal(lst &sym_lst, lst &repl_lst, int level) const
1625 new_seq.reserve(seq.size());
1627 epvector::const_iterator it = seq.begin(), itend = seq.end();
1628 while (it != itend) {
1629 new_seq.push_back(expair(it->rest.normal(), it->coeff));
1632 ex n = pseries(relational(var,point), new_seq);
1633 return (new lst(replace_with_symbol(n, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1637 /** Normalization of rational functions.
1638 * This function converts an expression to its normal form
1639 * "numerator/denominator", where numerator and denominator are (relatively
1640 * prime) polynomials. Any subexpressions which are not rational functions
1641 * (like non-rational numbers, non-integer powers or functions like Sin(),
1642 * Cos() etc.) are replaced by temporary symbols which are re-substituted by
1643 * the (normalized) subexpressions before normal() returns (this way, any
1644 * expression can be treated as a rational function). normal() is applied
1645 * recursively to arguments of functions etc.
1647 * @param level maximum depth of recursion
1648 * @return normalized expression */
1649 ex ex::normal(int level) const
1651 lst sym_lst, repl_lst;
1653 ex e = bp->normal(sym_lst, repl_lst, level);
1654 GINAC_ASSERT(is_ex_of_type(e, lst));
1656 // Re-insert replaced symbols
1657 if (sym_lst.nops() > 0)
1658 e = e.subs(sym_lst, repl_lst);
1660 // Convert {numerator, denominator} form back to fraction
1661 return e.op(0) / e.op(1);
1664 /** Numerator of an expression. If the expression is not of the normal form
1665 * "numerator/denominator", it is first converted to this form and then the
1666 * numerator is returned.
1669 * @return numerator */
1670 ex ex::numer(void) const
1672 lst sym_lst, repl_lst;
1674 ex e = bp->normal(sym_lst, repl_lst, 0);
1675 GINAC_ASSERT(is_ex_of_type(e, lst));
1677 // Re-insert replaced symbols
1678 if (sym_lst.nops() > 0)
1679 return e.op(0).subs(sym_lst, repl_lst);
1684 /** Denominator of an expression. If the expression is not of the normal form
1685 * "numerator/denominator", it is first converted to this form and then the
1686 * denominator is returned.
1689 * @return denominator */
1690 ex ex::denom(void) const
1692 lst sym_lst, repl_lst;
1694 ex e = bp->normal(sym_lst, repl_lst, 0);
1695 GINAC_ASSERT(is_ex_of_type(e, lst));
1697 // Re-insert replaced symbols
1698 if (sym_lst.nops() > 0)
1699 return e.op(1).subs(sym_lst, repl_lst);
1704 #ifndef NO_NAMESPACE_GINAC
1705 } // namespace GiNaC
1706 #endif // ndef NO_NAMESPACE_GINAC