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 // Sort c and d so that c has higher degree
816 int adeg = a.degree(*x), bdeg = b.degree(*x);
830 // Remove content from c and d, to be attached to GCD later
831 ex cont_c = c.content(*x);
832 ex cont_d = d.content(*x);
833 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
836 c = c.primpart(*x, cont_c);
837 d = d.primpart(*x, cont_d);
839 // First element of subresultant sequence
840 ex r = _ex0(), ri = _ex1(), psi = _ex1();
841 int delta = cdeg - ddeg;
844 // Calculate polynomial pseudo-remainder
845 r = prem(c, d, *x, false);
847 return gamma * d.primpart(*x);
850 if (!divide(r, ri * power(psi, delta), d, false))
851 throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
854 if (is_ex_exactly_of_type(r, numeric))
857 return gamma * r.primpart(*x);
860 // Next element of subresultant sequence
861 ri = c.expand().lcoeff(*x);
865 divide(power(ri, delta), power(psi, delta-1), psi, false);
871 /** Return maximum (absolute value) coefficient of a polynomial.
872 * This function is used internally by heur_gcd().
874 * @param e expanded multivariate polynomial
875 * @return maximum coefficient
878 numeric ex::max_coefficient(void) const
881 return bp->max_coefficient();
884 numeric basic::max_coefficient(void) const
889 numeric numeric::max_coefficient(void) const
894 numeric add::max_coefficient(void) const
896 epvector::const_iterator it = seq.begin();
897 epvector::const_iterator itend = seq.end();
898 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
899 numeric cur_max = abs(ex_to_numeric(overall_coeff));
900 while (it != itend) {
902 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
903 a = abs(ex_to_numeric(it->coeff));
911 numeric mul::max_coefficient(void) const
913 #ifdef DO_GINAC_ASSERT
914 epvector::const_iterator it = seq.begin();
915 epvector::const_iterator itend = seq.end();
916 while (it != itend) {
917 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
920 #endif // def DO_GINAC_ASSERT
921 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
922 return abs(ex_to_numeric(overall_coeff));
926 /** Apply symmetric modular homomorphism to a multivariate polynomial.
927 * This function is used internally by heur_gcd().
929 * @param e expanded multivariate polynomial
931 * @return mapped polynomial
934 ex ex::smod(const numeric &xi) const
940 ex basic::smod(const numeric &xi) const
945 ex numeric::smod(const numeric &xi) const
947 #ifndef NO_NAMESPACE_GINAC
948 return GiNaC::smod(*this, xi);
949 #else // ndef NO_NAMESPACE_GINAC
950 return ::smod(*this, xi);
951 #endif // ndef NO_NAMESPACE_GINAC
954 ex add::smod(const numeric &xi) const
957 newseq.reserve(seq.size()+1);
958 epvector::const_iterator it = seq.begin();
959 epvector::const_iterator itend = seq.end();
960 while (it != itend) {
961 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
962 #ifndef NO_NAMESPACE_GINAC
963 numeric coeff = GiNaC::smod(ex_to_numeric(it->coeff), xi);
964 #else // ndef NO_NAMESPACE_GINAC
965 numeric coeff = ::smod(ex_to_numeric(it->coeff), xi);
966 #endif // ndef NO_NAMESPACE_GINAC
967 if (!coeff.is_zero())
968 newseq.push_back(expair(it->rest, coeff));
971 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
972 #ifndef NO_NAMESPACE_GINAC
973 numeric coeff = GiNaC::smod(ex_to_numeric(overall_coeff), xi);
974 #else // ndef NO_NAMESPACE_GINAC
975 numeric coeff = ::smod(ex_to_numeric(overall_coeff), xi);
976 #endif // ndef NO_NAMESPACE_GINAC
977 return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
980 ex mul::smod(const numeric &xi) const
982 #ifdef DO_GINAC_ASSERT
983 epvector::const_iterator it = seq.begin();
984 epvector::const_iterator itend = seq.end();
985 while (it != itend) {
986 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
989 #endif // def DO_GINAC_ASSERT
990 mul * mulcopyp=new mul(*this);
991 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
992 #ifndef NO_NAMESPACE_GINAC
993 mulcopyp->overall_coeff = GiNaC::smod(ex_to_numeric(overall_coeff),xi);
994 #else // ndef NO_NAMESPACE_GINAC
995 mulcopyp->overall_coeff = ::smod(ex_to_numeric(overall_coeff),xi);
996 #endif // ndef NO_NAMESPACE_GINAC
997 mulcopyp->clearflag(status_flags::evaluated);
998 mulcopyp->clearflag(status_flags::hash_calculated);
999 return mulcopyp->setflag(status_flags::dynallocated);
1003 /** Exception thrown by heur_gcd() to signal failure. */
1004 class gcdheu_failed {};
1006 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1007 * get_symbol_stats() must have been called previously with the input
1008 * polynomials and an iterator to the first element of the sym_desc vector
1009 * passed in. This function is used internally by gcd().
1011 * @param a first multivariate polynomial (expanded)
1012 * @param b second multivariate polynomial (expanded)
1013 * @param ca cofactor of polynomial a (returned), NULL to suppress
1014 * calculation of cofactor
1015 * @param cb cofactor of polynomial b (returned), NULL to suppress
1016 * calculation of cofactor
1017 * @param var iterator to first element of vector of sym_desc structs
1018 * @return the GCD as a new expression
1020 * @exception gcdheu_failed() */
1022 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
1024 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1025 numeric g = gcd(ex_to_numeric(a), ex_to_numeric(b));
1030 *ca = ex_to_numeric(a).mul(rg);
1032 *cb = ex_to_numeric(b).mul(rg);
1036 // The first symbol is our main variable
1037 const symbol *x = var->sym;
1039 // Remove integer content
1040 numeric gc = gcd(a.integer_content(), b.integer_content());
1041 numeric rgc = gc.inverse();
1044 int maxdeg = max(p.degree(*x), q.degree(*x));
1046 // Find evaluation point
1047 numeric mp = p.max_coefficient(), mq = q.max_coefficient();
1050 xi = mq * _num2() + _num2();
1052 xi = mp * _num2() + _num2();
1055 for (int t=0; t<6; t++) {
1056 if (xi.int_length() * maxdeg > 50000)
1057 throw gcdheu_failed();
1059 // Apply evaluation homomorphism and calculate GCD
1060 ex gamma = heur_gcd(p.subs(*x == xi), q.subs(*x == xi), NULL, NULL, var+1).expand();
1061 if (!is_ex_exactly_of_type(gamma, fail)) {
1063 // Reconstruct polynomial from GCD of mapped polynomials
1065 numeric rxi = xi.inverse();
1066 for (int i=0; !gamma.is_zero(); i++) {
1067 ex gi = gamma.smod(xi);
1068 g += gi * power(*x, i);
1069 gamma = (gamma - gi) * rxi;
1071 // Remove integer content
1072 g /= g.integer_content();
1074 // If the calculated polynomial divides both a and b, this is the GCD
1076 if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1078 ex lc = g.lcoeff(*x);
1079 if (is_ex_exactly_of_type(lc, numeric) && ex_to_numeric(lc).is_negative())
1086 // Next evaluation point
1087 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1089 return *new ex(fail());
1093 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1096 * @param a first multivariate polynomial
1097 * @param b second multivariate polynomial
1098 * @param check_args check whether a and b are polynomials with rational
1099 * coefficients (defaults to "true")
1100 * @return the GCD as a new expression */
1102 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1104 // Partially factored cases (to avoid expanding large expressions)
1105 if (is_ex_exactly_of_type(a, mul)) {
1106 if (is_ex_exactly_of_type(b, mul) && b.nops() > a.nops())
1112 for (unsigned i=0; i<a.nops(); i++) {
1113 ex part_ca, part_cb;
1114 g *= gcd(a.op(i), part_b, &part_ca, &part_cb, check_args);
1123 } else if (is_ex_exactly_of_type(b, mul)) {
1124 if (is_ex_exactly_of_type(a, mul) && a.nops() > b.nops())
1130 for (unsigned i=0; i<b.nops(); i++) {
1131 ex part_ca, part_cb;
1132 g *= gcd(part_a, b.op(i), &part_ca, &part_cb, check_args);
1143 // Some trivial cases
1144 ex aex = a.expand(), bex = b.expand();
1145 if (aex.is_zero()) {
1152 if (bex.is_zero()) {
1159 if (aex.is_equal(_ex1()) || bex.is_equal(_ex1())) {
1167 if (a.is_equal(b)) {
1175 if (is_ex_exactly_of_type(aex, numeric) && is_ex_exactly_of_type(bex, numeric)) {
1176 numeric g = gcd(ex_to_numeric(aex), ex_to_numeric(bex));
1178 *ca = ex_to_numeric(aex) / g;
1180 *cb = ex_to_numeric(bex) / g;
1183 if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)) {
1184 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1187 // Gather symbol statistics
1188 sym_desc_vec sym_stats;
1189 get_symbol_stats(a, b, sym_stats);
1191 // The symbol with least degree is our main variable
1192 sym_desc_vec::const_iterator var = sym_stats.begin();
1193 const symbol *x = var->sym;
1195 // Cancel trivial common factor
1196 int ldeg_a = var->ldeg_a;
1197 int ldeg_b = var->ldeg_b;
1198 int min_ldeg = min(ldeg_a, ldeg_b);
1200 ex common = power(*x, min_ldeg);
1201 //clog << "trivial common factor " << common << endl;
1202 return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1205 // Try to eliminate variables
1206 if (var->deg_a == 0) {
1207 //clog << "eliminating variable " << *x << " from b" << endl;
1208 ex c = bex.content(*x);
1209 ex g = gcd(aex, c, ca, cb, false);
1211 *cb *= bex.unit(*x) * bex.primpart(*x, c);
1213 } else if (var->deg_b == 0) {
1214 //clog << "eliminating variable " << *x << " from a" << endl;
1215 ex c = aex.content(*x);
1216 ex g = gcd(c, bex, ca, cb, false);
1218 *ca *= aex.unit(*x) * aex.primpart(*x, c);
1222 // Try heuristic algorithm first, fall back to PRS if that failed
1225 g = heur_gcd(aex, bex, ca, cb, var);
1226 } catch (gcdheu_failed) {
1227 g = *new ex(fail());
1229 if (is_ex_exactly_of_type(g, fail)) {
1230 //clog << "heuristics failed" << endl;
1231 g = sr_gcd(aex, bex, x);
1233 divide(aex, g, *ca, false);
1235 divide(bex, g, *cb, false);
1241 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1243 * @param a first multivariate polynomial
1244 * @param b second multivariate polynomial
1245 * @param check_args check whether a and b are polynomials with rational
1246 * coefficients (defaults to "true")
1247 * @return the LCM as a new expression */
1248 ex lcm(const ex &a, const ex &b, bool check_args)
1250 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
1251 return lcm(ex_to_numeric(a), ex_to_numeric(b));
1252 if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1253 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1256 ex g = gcd(a, b, &ca, &cb, false);
1262 * Square-free factorization
1265 // Univariate GCD of polynomials in Q[x] (used internally by sqrfree()).
1266 // a and b can be multivariate polynomials but they are treated as univariate polynomials in x.
1267 static ex univariate_gcd(const ex &a, const ex &b, const symbol &x)
1273 if (a.is_equal(_ex1()) || b.is_equal(_ex1()))
1275 if (is_ex_of_type(a, numeric) && is_ex_of_type(b, numeric))
1276 return gcd(ex_to_numeric(a), ex_to_numeric(b));
1277 if (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1278 throw(std::invalid_argument("univariate_gcd: arguments must be polynomials over the rationals"));
1280 // Euclidean algorithm
1282 if (a.degree(x) >= b.degree(x)) {
1290 r = rem(c, d, x, false);
1296 return d / d.lcoeff(x);
1300 /** Compute square-free factorization of multivariate polynomial a(x) using
1303 * @param a multivariate polynomial
1304 * @param x variable to factor in
1305 * @return factored polynomial */
1306 ex sqrfree(const ex &a, const symbol &x)
1311 ex c = univariate_gcd(a, b, x);
1313 if (c.is_equal(_ex1())) {
1317 ex y = quo(b, c, x);
1318 ex z = y - w.diff(x);
1319 while (!z.is_zero()) {
1320 ex g = univariate_gcd(w, z, x);
1328 return res * power(w, i);
1333 * Normal form of rational functions
1337 * Note: The internal normal() functions (= basic::normal() and overloaded
1338 * functions) all return lists of the form {numerator, denominator}. This
1339 * is to get around mul::eval()'s automatic expansion of numeric coefficients.
1340 * E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
1341 * the information that (a+b) is the numerator and 3 is the denominator.
1344 /** Create a symbol for replacing the expression "e" (or return a previously
1345 * assigned symbol). The symbol is appended to sym_list and returned, the
1346 * expression is appended to repl_list.
1347 * @see ex::normal */
1348 static ex replace_with_symbol(const ex &e, lst &sym_lst, lst &repl_lst)
1350 // Expression already in repl_lst? Then return the assigned symbol
1351 for (unsigned i=0; i<repl_lst.nops(); i++)
1352 if (repl_lst.op(i).is_equal(e))
1353 return sym_lst.op(i);
1355 // Otherwise create new symbol and add to list, taking care that the
1356 // replacement expression doesn't contain symbols from the sym_lst
1357 // because subs() is not recursive
1360 ex e_replaced = e.subs(sym_lst, repl_lst);
1362 repl_lst.append(e_replaced);
1367 /** Default implementation of ex::normal(). It replaces the object with a
1369 * @see ex::normal */
1370 ex basic::normal(lst &sym_lst, lst &repl_lst, int level) const
1372 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1376 /** Implementation of ex::normal() for symbols. This returns the unmodified symbol.
1377 * @see ex::normal */
1378 ex symbol::normal(lst &sym_lst, lst &repl_lst, int level) const
1380 return (new lst(*this, _ex1()))->setflag(status_flags::dynallocated);
1384 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1385 * into re+I*im and replaces I and non-rational real numbers with a temporary
1387 * @see ex::normal */
1388 ex numeric::normal(lst &sym_lst, lst &repl_lst, int level) const
1390 numeric num = numer();
1393 if (num.is_real()) {
1394 if (!num.is_integer())
1395 numex = replace_with_symbol(numex, sym_lst, repl_lst);
1397 numeric re = num.real(), im = num.imag();
1398 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, sym_lst, repl_lst);
1399 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, sym_lst, repl_lst);
1400 numex = re_ex + im_ex * replace_with_symbol(I, sym_lst, repl_lst);
1403 // Denominator is always a real integer (see numeric::denom())
1404 return (new lst(numex, denom()))->setflag(status_flags::dynallocated);
1408 /** Fraction cancellation.
1409 * @param n numerator
1410 * @param d denominator
1411 * @return cancelled fraction {n, d} as a list */
1412 static ex frac_cancel(const ex &n, const ex &d)
1416 numeric pre_factor = _num1();
1418 //clog << "frac_cancel num = " << num << ", den = " << den << endl;
1420 // Handle special cases where numerator or denominator is 0
1422 return (new lst(_ex0(), _ex1()))->setflag(status_flags::dynallocated);
1423 if (den.expand().is_zero())
1424 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
1426 // Bring numerator and denominator to Z[X] by multiplying with
1427 // LCM of all coefficients' denominators
1428 numeric num_lcm = lcm_of_coefficients_denominators(num);
1429 numeric den_lcm = lcm_of_coefficients_denominators(den);
1430 num = multiply_lcm(num, num_lcm);
1431 den = multiply_lcm(den, den_lcm);
1432 pre_factor = den_lcm / num_lcm;
1434 // Cancel GCD from numerator and denominator
1436 if (gcd(num, den, &cnum, &cden, false) != _ex1()) {
1441 // Make denominator unit normal (i.e. coefficient of first symbol
1442 // as defined by get_first_symbol() is made positive)
1444 if (get_first_symbol(den, x)) {
1445 GINAC_ASSERT(is_ex_exactly_of_type(den.unit(*x),numeric));
1446 if (ex_to_numeric(den.unit(*x)).is_negative()) {
1452 // Return result as list
1453 //clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << endl;
1454 return (new lst(num * pre_factor.numer(), den * pre_factor.denom()))->setflag(status_flags::dynallocated);
1458 /** Implementation of ex::normal() for a sum. It expands terms and performs
1459 * fractional addition.
1460 * @see ex::normal */
1461 ex add::normal(lst &sym_lst, lst &repl_lst, int level) const
1463 // Normalize and expand children, chop into summands
1465 o.reserve(seq.size()+1);
1466 epvector::const_iterator it = seq.begin(), itend = seq.end();
1467 while (it != itend) {
1469 // Normalize and expand child
1470 ex n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1).expand();
1472 // If numerator is a sum, chop into summands
1473 if (is_ex_exactly_of_type(n.op(0), add)) {
1474 epvector::const_iterator bit = ex_to_add(n.op(0)).seq.begin(), bitend = ex_to_add(n.op(0)).seq.end();
1475 while (bit != bitend) {
1476 o.push_back((new lst(recombine_pair_to_ex(*bit), n.op(1)))->setflag(status_flags::dynallocated));
1480 // The overall_coeff is already normalized (== rational), we just
1481 // split it into numerator and denominator
1482 GINAC_ASSERT(ex_to_numeric(ex_to_add(n.op(0)).overall_coeff).is_rational());
1483 numeric overall = ex_to_numeric(ex_to_add(n.op(0)).overall_coeff);
1484 o.push_back((new lst(overall.numer(), overall.denom() * n.op(1)))->setflag(status_flags::dynallocated));
1489 o.push_back(overall_coeff.bp->normal(sym_lst, repl_lst, level-1));
1491 // o is now a vector of {numerator, denominator} lists
1493 // Determine common denominator
1495 exvector::const_iterator ait = o.begin(), aitend = o.end();
1496 //clog << "add::normal uses the following summands:\n";
1497 while (ait != aitend) {
1498 //clog << " num = " << ait->op(0) << ", den = " << ait->op(1) << endl;
1499 den = lcm(ait->op(1), den, false);
1502 //clog << " common denominator = " << den << endl;
1505 if (den.is_equal(_ex1())) {
1507 // Common denominator is 1, simply add all numerators
1509 for (ait=o.begin(); ait!=aitend; ait++) {
1510 num_seq.push_back(ait->op(0));
1512 return (new lst((new add(num_seq))->setflag(status_flags::dynallocated), den))->setflag(status_flags::dynallocated);
1516 // Perform fractional addition
1518 for (ait=o.begin(); ait!=aitend; ait++) {
1520 if (!divide(den, ait->op(1), q, false)) {
1521 // should not happen
1522 throw(std::runtime_error("invalid expression in add::normal, division failed"));
1524 num_seq.push_back((ait->op(0) * q).expand());
1526 ex num = (new add(num_seq))->setflag(status_flags::dynallocated);
1528 // Cancel common factors from num/den
1529 return frac_cancel(num, den);
1534 /** Implementation of ex::normal() for a product. It cancels common factors
1536 * @see ex::normal() */
1537 ex mul::normal(lst &sym_lst, lst &repl_lst, int level) const
1539 // Normalize children, separate into numerator and denominator
1543 epvector::const_iterator it = seq.begin(), itend = seq.end();
1544 while (it != itend) {
1545 n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1);
1550 n = overall_coeff.bp->normal(sym_lst, repl_lst, level-1);
1554 // Perform fraction cancellation
1555 return frac_cancel(num, den);
1559 /** Implementation of ex::normal() for powers. It normalizes the basis,
1560 * distributes integer exponents to numerator and denominator, and replaces
1561 * non-integer powers by temporary symbols.
1562 * @see ex::normal */
1563 ex power::normal(lst &sym_lst, lst &repl_lst, int level) const
1566 ex n = basis.bp->normal(sym_lst, repl_lst, level-1);
1568 if (exponent.info(info_flags::integer)) {
1570 if (exponent.info(info_flags::positive)) {
1572 // (a/b)^n -> {a^n, b^n}
1573 return (new lst(power(n.op(0), exponent), power(n.op(1), exponent)))->setflag(status_flags::dynallocated);
1575 } else if (exponent.info(info_flags::negint)) {
1577 // (a/b)^-n -> {b^n, a^n}
1578 return (new lst(power(n.op(1), -exponent), power(n.op(0), -exponent)))->setflag(status_flags::dynallocated);
1582 if (exponent.info(info_flags::positive)) {
1584 // (a/b)^z -> {sym((a/b)^z), 1}
1585 return (new lst(replace_with_symbol(power(n.op(0) / n.op(1), exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1589 if (n.op(1).is_equal(_ex1())) {
1591 // a^-x -> {1, sym(a^x)}
1592 return (new lst(_ex1(), replace_with_symbol(power(n.op(0), -exponent), sym_lst, repl_lst)))->setflag(status_flags::dynallocated);
1596 // (a/b)^-x -> {(b/a)^x, 1}
1597 return (new lst(replace_with_symbol(power(n.op(1) / n.op(0), -exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1604 /** Implementation of ex::normal() for pseries. It normalizes each coefficient and
1605 * replaces the series by a temporary symbol.
1606 * @see ex::normal */
1607 ex pseries::normal(lst &sym_lst, lst &repl_lst, int level) const
1610 new_seq.reserve(seq.size());
1612 epvector::const_iterator it = seq.begin(), itend = seq.end();
1613 while (it != itend) {
1614 new_seq.push_back(expair(it->rest.normal(), it->coeff));
1617 ex n = pseries(var, point, new_seq);
1618 return (new lst(replace_with_symbol(n, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1622 /** Normalization of rational functions.
1623 * This function converts an expression to its normal form
1624 * "numerator/denominator", where numerator and denominator are (relatively
1625 * prime) polynomials. Any subexpressions which are not rational functions
1626 * (like non-rational numbers, non-integer powers or functions like Sin(),
1627 * Cos() etc.) are replaced by temporary symbols which are re-substituted by
1628 * the (normalized) subexpressions before normal() returns (this way, any
1629 * expression can be treated as a rational function). normal() is applied
1630 * recursively to arguments of functions etc.
1632 * @param level maximum depth of recursion
1633 * @return normalized expression */
1634 ex ex::normal(int level) const
1636 lst sym_lst, repl_lst;
1638 ex e = bp->normal(sym_lst, repl_lst, level);
1639 GINAC_ASSERT(is_ex_of_type(e, lst));
1641 // Re-insert replaced symbols
1642 if (sym_lst.nops() > 0)
1643 e = e.subs(sym_lst, repl_lst);
1645 // Convert {numerator, denominator} form back to fraction
1646 return e.op(0) / e.op(1);
1649 /** Numerator of an expression. If the expression is not of the normal form
1650 * "numerator/denominator", it is first converted to this form and then the
1651 * numerator is returned.
1654 * @return numerator */
1655 ex ex::numer(void) const
1657 lst sym_lst, repl_lst;
1659 ex e = bp->normal(sym_lst, repl_lst, 0);
1660 GINAC_ASSERT(is_ex_of_type(e, lst));
1662 // Re-insert replaced symbols
1663 if (sym_lst.nops() > 0)
1664 return e.op(0).subs(sym_lst, repl_lst);
1669 /** Denominator of an expression. If the expression is not of the normal form
1670 * "numerator/denominator", it is first converted to this form and then the
1671 * denominator is returned.
1674 * @return denominator */
1675 ex ex::denom(void) const
1677 lst sym_lst, repl_lst;
1679 ex e = bp->normal(sym_lst, repl_lst, 0);
1680 GINAC_ASSERT(is_ex_of_type(e, lst));
1682 // Re-insert replaced symbols
1683 if (sym_lst.nops() > 0)
1684 return e.op(1).subs(sym_lst, repl_lst);
1689 #ifndef NO_NAMESPACE_GINAC
1690 } // namespace GiNaC
1691 #endif // ndef NO_NAMESPACE_GINAC