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. */
9 * GiNaC Copyright (C) 1999-2000 Johannes Gutenberg University Mainz, Germany
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
35 #include "expairseq.h"
44 #include "relational.h"
49 #ifndef NO_NAMESPACE_GINAC
51 #endif // ndef NO_NAMESPACE_GINAC
53 // If comparing expressions (ex::compare()) is fast, you can set this to 1.
54 // Some routines like quo(), rem() and gcd() will then return a quick answer
55 // when they are called with two identical arguments.
56 #define FAST_COMPARE 1
58 // Set this if you want divide_in_z() to use remembering
59 #define USE_REMEMBER 0
61 // Set this if you want divide_in_z() to use trial division followed by
62 // polynomial interpolation (usually slower except for very large problems)
63 #define USE_TRIAL_DIVISION 0
65 // Set this to enable some statistical output for the GCD routines
70 // Statistics variables
71 static int gcd_called = 0;
72 static int sr_gcd_called = 0;
73 static int heur_gcd_called = 0;
74 static int heur_gcd_failed = 0;
76 // Print statistics at end of program
77 static struct _stat_print {
80 cout << "gcd() called " << gcd_called << " times\n";
81 cout << "sr_gcd() called " << sr_gcd_called << " times\n";
82 cout << "heur_gcd() called " << heur_gcd_called << " times\n";
83 cout << "heur_gcd() failed " << heur_gcd_failed << " times\n";
89 /** Return pointer to first symbol found in expression. Due to GiNaCĀ“s
90 * internal ordering of terms, it may not be obvious which symbol this
91 * function returns for a given expression.
93 * @param e expression to search
94 * @param x pointer to first symbol found (returned)
95 * @return "false" if no symbol was found, "true" otherwise */
96 static bool get_first_symbol(const ex &e, const symbol *&x)
98 if (is_ex_exactly_of_type(e, symbol)) {
99 x = static_cast<symbol *>(e.bp);
101 } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
102 for (unsigned i=0; i<e.nops(); i++)
103 if (get_first_symbol(e.op(i), x))
105 } else if (is_ex_exactly_of_type(e, power)) {
106 if (get_first_symbol(e.op(0), x))
114 * Statistical information about symbols in polynomials
117 /** This structure holds information about the highest and lowest degrees
118 * in which a symbol appears in two multivariate polynomials "a" and "b".
119 * A vector of these structures with information about all symbols in
120 * two polynomials can be created with the function get_symbol_stats().
122 * @see get_symbol_stats */
124 /** Pointer to symbol */
127 /** Highest degree of symbol in polynomial "a" */
130 /** Highest degree of symbol in polynomial "b" */
133 /** Lowest degree of symbol in polynomial "a" */
136 /** Lowest degree of symbol in polynomial "b" */
139 /** Maximum of deg_a and deg_b (Used for sorting) */
142 /** Commparison operator for sorting */
143 bool operator<(const sym_desc &x) const {return max_deg < x.max_deg;}
146 // Vector of sym_desc structures
147 typedef vector<sym_desc> sym_desc_vec;
149 // Add symbol the sym_desc_vec (used internally by get_symbol_stats())
150 static void add_symbol(const symbol *s, sym_desc_vec &v)
152 sym_desc_vec::iterator it = v.begin(), itend = v.end();
153 while (it != itend) {
154 if (it->sym->compare(*s) == 0) // If it's already in there, don't add it a second time
163 // Collect all symbols of an expression (used internally by get_symbol_stats())
164 static void collect_symbols(const ex &e, sym_desc_vec &v)
166 if (is_ex_exactly_of_type(e, symbol)) {
167 add_symbol(static_cast<symbol *>(e.bp), v);
168 } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
169 for (unsigned i=0; i<e.nops(); i++)
170 collect_symbols(e.op(i), v);
171 } else if (is_ex_exactly_of_type(e, power)) {
172 collect_symbols(e.op(0), v);
176 /** Collect statistical information about symbols in polynomials.
177 * This function fills in a vector of "sym_desc" structs which contain
178 * information about the highest and lowest degrees of all symbols that
179 * appear in two polynomials. The vector is then sorted by minimum
180 * degree (lowest to highest). The information gathered by this
181 * function is used by the GCD routines to identify trivial factors
182 * and to determine which variable to choose as the main variable
183 * for GCD computation.
185 * @param a first multivariate polynomial
186 * @param b second multivariate polynomial
187 * @param v vector of sym_desc structs (filled in) */
188 static void get_symbol_stats(const ex &a, const ex &b, sym_desc_vec &v)
190 collect_symbols(a.eval(), v); // eval() to expand assigned symbols
191 collect_symbols(b.eval(), v);
192 sym_desc_vec::iterator it = v.begin(), itend = v.end();
193 while (it != itend) {
194 int deg_a = a.degree(*(it->sym));
195 int deg_b = b.degree(*(it->sym));
198 it->max_deg = max(deg_a, deg_b);
199 it->ldeg_a = a.ldegree(*(it->sym));
200 it->ldeg_b = b.ldegree(*(it->sym));
203 sort(v.begin(), v.end());
205 clog << "Symbols:\n";
206 it = v.begin(); itend = v.end();
207 while (it != itend) {
208 clog << " " << *it->sym << ": deg_a=" << it->deg_a << ", deg_b=" << it->deg_b << ", ldeg_a=" << it->ldeg_a << ", ldeg_b=" << it->ldeg_b << ", max_deg=" << it->max_deg << endl;
209 clog << " lcoeff_a=" << a.lcoeff(*(it->sym)) << ", lcoeff_b=" << b.lcoeff(*(it->sym)) << endl;
217 * Computation of LCM of denominators of coefficients of a polynomial
220 // Compute LCM of denominators of coefficients by going through the
221 // expression recursively (used internally by lcm_of_coefficients_denominators())
222 static numeric lcmcoeff(const ex &e, const numeric &l)
224 if (e.info(info_flags::rational))
225 return lcm(ex_to_numeric(e).denom(), l);
226 else if (is_ex_exactly_of_type(e, add)) {
228 for (unsigned i=0; i<e.nops(); i++)
229 c = lcmcoeff(e.op(i), c);
231 } else if (is_ex_exactly_of_type(e, mul)) {
233 for (unsigned i=0; i<e.nops(); i++)
234 c *= lcmcoeff(e.op(i), _num1());
236 } else if (is_ex_exactly_of_type(e, power))
237 return pow(lcmcoeff(e.op(0), l), ex_to_numeric(e.op(1)));
241 /** Compute LCM of denominators of coefficients of a polynomial.
242 * Given a polynomial with rational coefficients, this function computes
243 * the LCM of the denominators of all coefficients. This can be used
244 * to bring a polynomial from Q[X] to Z[X].
246 * @param e multivariate polynomial (need not be expanded)
247 * @return LCM of denominators of coefficients */
248 static numeric lcm_of_coefficients_denominators(const ex &e)
250 return lcmcoeff(e, _num1());
253 /** Bring polynomial from Q[X] to Z[X] by multiplying in the previously
254 * determined LCM of the coefficient's denominators.
256 * @param e multivariate polynomial (need not be expanded)
257 * @param lcm LCM to multiply in */
258 static ex multiply_lcm(const ex &e, const numeric &lcm)
260 if (is_ex_exactly_of_type(e, mul)) {
262 numeric lcm_accum = _num1();
263 for (unsigned i=0; i<e.nops(); i++) {
264 numeric op_lcm = lcmcoeff(e.op(i), _num1());
265 c *= multiply_lcm(e.op(i), op_lcm);
268 c *= lcm / lcm_accum;
270 } else if (is_ex_exactly_of_type(e, add)) {
272 for (unsigned i=0; i<e.nops(); i++)
273 c += multiply_lcm(e.op(i), lcm);
275 } else if (is_ex_exactly_of_type(e, power)) {
276 return pow(multiply_lcm(e.op(0), lcm.power(ex_to_numeric(e.op(1)).inverse())), e.op(1));
282 /** Compute the integer content (= GCD of all numeric coefficients) of an
283 * expanded polynomial.
285 * @param e expanded polynomial
286 * @return integer content */
287 numeric ex::integer_content(void) const
290 return bp->integer_content();
293 numeric basic::integer_content(void) const
298 numeric numeric::integer_content(void) const
303 numeric add::integer_content(void) const
305 epvector::const_iterator it = seq.begin();
306 epvector::const_iterator itend = seq.end();
308 while (it != itend) {
309 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
310 GINAC_ASSERT(is_ex_exactly_of_type(it->coeff,numeric));
311 c = gcd(ex_to_numeric(it->coeff), c);
314 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
315 c = gcd(ex_to_numeric(overall_coeff),c);
319 numeric mul::integer_content(void) const
321 #ifdef DO_GINAC_ASSERT
322 epvector::const_iterator it = seq.begin();
323 epvector::const_iterator itend = seq.end();
324 while (it != itend) {
325 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
328 #endif // def DO_GINAC_ASSERT
329 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
330 return abs(ex_to_numeric(overall_coeff));
335 * Polynomial quotients and remainders
338 /** Quotient q(x) of polynomials a(x) and b(x) in Q[x].
339 * It satisfies a(x)=b(x)*q(x)+r(x).
341 * @param a first polynomial in x (dividend)
342 * @param b second polynomial in x (divisor)
343 * @param x a and b are polynomials in x
344 * @param check_args check whether a and b are polynomials with rational
345 * coefficients (defaults to "true")
346 * @return quotient of a and b in Q[x] */
347 ex quo(const ex &a, const ex &b, const symbol &x, bool check_args)
350 throw(std::overflow_error("quo: division by zero"));
351 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
357 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
358 throw(std::invalid_argument("quo: arguments must be polynomials over the rationals"));
360 // Polynomial long division
365 int bdeg = b.degree(x);
366 int rdeg = r.degree(x);
367 ex blcoeff = b.expand().coeff(x, bdeg);
368 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
369 while (rdeg >= bdeg) {
370 ex term, rcoeff = r.coeff(x, rdeg);
371 if (blcoeff_is_numeric)
372 term = rcoeff / blcoeff;
374 if (!divide(rcoeff, blcoeff, term, false))
375 return *new ex(fail());
377 term *= power(x, rdeg - bdeg);
379 r -= (term * b).expand();
388 /** Remainder r(x) of polynomials a(x) and b(x) in Q[x].
389 * It satisfies a(x)=b(x)*q(x)+r(x).
391 * @param a first polynomial in x (dividend)
392 * @param b second polynomial in x (divisor)
393 * @param x a and b are polynomials in x
394 * @param check_args check whether a and b are polynomials with rational
395 * coefficients (defaults to "true")
396 * @return remainder of a(x) and b(x) in Q[x] */
397 ex rem(const ex &a, const ex &b, const symbol &x, bool check_args)
400 throw(std::overflow_error("rem: division by zero"));
401 if (is_ex_exactly_of_type(a, numeric)) {
402 if (is_ex_exactly_of_type(b, numeric))
411 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
412 throw(std::invalid_argument("rem: arguments must be polynomials over the rationals"));
414 // Polynomial long division
418 int bdeg = b.degree(x);
419 int rdeg = r.degree(x);
420 ex blcoeff = b.expand().coeff(x, bdeg);
421 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
422 while (rdeg >= bdeg) {
423 ex term, rcoeff = r.coeff(x, rdeg);
424 if (blcoeff_is_numeric)
425 term = rcoeff / blcoeff;
427 if (!divide(rcoeff, blcoeff, term, false))
428 return *new ex(fail());
430 term *= power(x, rdeg - bdeg);
431 r -= (term * b).expand();
440 /** Pseudo-remainder of polynomials a(x) and b(x) in Z[x].
442 * @param a first polynomial in x (dividend)
443 * @param b second polynomial in x (divisor)
444 * @param x a and b are polynomials in x
445 * @param check_args check whether a and b are polynomials with rational
446 * coefficients (defaults to "true")
447 * @return pseudo-remainder of a(x) and b(x) in Z[x] */
448 ex prem(const ex &a, const ex &b, const symbol &x, bool check_args)
451 throw(std::overflow_error("prem: division by zero"));
452 if (is_ex_exactly_of_type(a, numeric)) {
453 if (is_ex_exactly_of_type(b, numeric))
458 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
459 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
461 // Polynomial long division
464 int rdeg = r.degree(x);
465 int bdeg = eb.degree(x);
468 blcoeff = eb.coeff(x, bdeg);
472 eb -= blcoeff * power(x, bdeg);
476 int delta = rdeg - bdeg + 1, i = 0;
477 while (rdeg >= bdeg && !r.is_zero()) {
478 ex rlcoeff = r.coeff(x, rdeg);
479 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
483 r -= rlcoeff * power(x, rdeg);
484 r = (blcoeff * r).expand() - term;
488 return power(blcoeff, delta - i) * r;
492 /** Sparse pseudo-remainder of polynomials a(x) and b(x) in Z[x].
494 * @param a first polynomial in x (dividend)
495 * @param b second polynomial in x (divisor)
496 * @param x a and b are polynomials in x
497 * @param check_args check whether a and b are polynomials with rational
498 * coefficients (defaults to "true")
499 * @return sparse pseudo-remainder of a(x) and b(x) in Z[x] */
501 ex sprem(const ex &a, const ex &b, const symbol &x, bool check_args)
504 throw(std::overflow_error("prem: division by zero"));
505 if (is_ex_exactly_of_type(a, numeric)) {
506 if (is_ex_exactly_of_type(b, numeric))
511 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
512 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
514 // Polynomial long division
517 int rdeg = r.degree(x);
518 int bdeg = eb.degree(x);
521 blcoeff = eb.coeff(x, bdeg);
525 eb -= blcoeff * power(x, bdeg);
529 while (rdeg >= bdeg && !r.is_zero()) {
530 ex rlcoeff = r.coeff(x, rdeg);
531 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
535 r -= rlcoeff * power(x, rdeg);
536 r = (blcoeff * r).expand() - term;
543 /** Exact polynomial division of a(X) by b(X) in Q[X].
545 * @param a first multivariate polynomial (dividend)
546 * @param b second multivariate polynomial (divisor)
547 * @param q quotient (returned)
548 * @param check_args check whether a and b are polynomials with rational
549 * coefficients (defaults to "true")
550 * @return "true" when exact division succeeds (quotient returned in q),
551 * "false" otherwise */
552 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
556 throw(std::overflow_error("divide: division by zero"));
559 if (is_ex_exactly_of_type(b, numeric)) {
562 } else if (is_ex_exactly_of_type(a, numeric))
570 if (check_args && (!a.info(info_flags::rational_polynomial) ||
571 !b.info(info_flags::rational_polynomial)))
572 throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
576 if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
577 throw(std::invalid_argument("invalid expression in divide()"));
579 // Polynomial long division (recursive)
583 int bdeg = b.degree(*x);
584 int rdeg = r.degree(*x);
585 ex blcoeff = b.expand().coeff(*x, bdeg);
586 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
587 while (rdeg >= bdeg) {
588 ex term, rcoeff = r.coeff(*x, rdeg);
589 if (blcoeff_is_numeric)
590 term = rcoeff / blcoeff;
592 if (!divide(rcoeff, blcoeff, term, false))
594 term *= power(*x, rdeg - bdeg);
596 r -= (term * b).expand();
610 typedef pair<ex, ex> ex2;
611 typedef pair<ex, bool> exbool;
614 bool operator() (const ex2 p, const ex2 q) const
616 return p.first.compare(q.first) < 0 || (!(q.first.compare(p.first) < 0) && p.second.compare(q.second) < 0);
620 typedef map<ex2, exbool, ex2_less> ex2_exbool_remember;
624 /** Exact polynomial division of a(X) by b(X) in Z[X].
625 * This functions works like divide() but the input and output polynomials are
626 * in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
627 * divide(), it doesnĀ“t check whether the input polynomials really are integer
628 * polynomials, so be careful of what you pass in. Also, you have to run
629 * get_symbol_stats() over the input polynomials before calling this function
630 * and pass an iterator to the first element of the sym_desc vector. This
631 * function is used internally by the heur_gcd().
633 * @param a first multivariate polynomial (dividend)
634 * @param b second multivariate polynomial (divisor)
635 * @param q quotient (returned)
636 * @param var iterator to first element of vector of sym_desc structs
637 * @return "true" when exact division succeeds (the quotient is returned in
638 * q), "false" otherwise.
639 * @see get_symbol_stats, heur_gcd */
640 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
644 throw(std::overflow_error("divide_in_z: division by zero"));
645 if (b.is_equal(_ex1())) {
649 if (is_ex_exactly_of_type(a, numeric)) {
650 if (is_ex_exactly_of_type(b, numeric)) {
652 return q.info(info_flags::integer);
665 static ex2_exbool_remember dr_remember;
666 ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
667 if (remembered != dr_remember.end()) {
668 q = remembered->second.first;
669 return remembered->second.second;
674 const symbol *x = var->sym;
677 int adeg = a.degree(*x), bdeg = b.degree(*x);
681 #if USE_TRIAL_DIVISION
683 // Trial division with polynomial interpolation
686 // Compute values at evaluation points 0..adeg
687 vector<numeric> alpha; alpha.reserve(adeg + 1);
688 exvector u; u.reserve(adeg + 1);
689 numeric point = _num0();
691 for (i=0; i<=adeg; i++) {
692 ex bs = b.subs(*x == point);
693 while (bs.is_zero()) {
695 bs = b.subs(*x == point);
697 if (!divide_in_z(a.subs(*x == point), bs, c, var+1))
699 alpha.push_back(point);
705 vector<numeric> rcp; rcp.reserve(adeg + 1);
706 rcp.push_back(_num0());
707 for (k=1; k<=adeg; k++) {
708 numeric product = alpha[k] - alpha[0];
710 product *= alpha[k] - alpha[i];
711 rcp.push_back(product.inverse());
714 // Compute Newton coefficients
715 exvector v; v.reserve(adeg + 1);
717 for (k=1; k<=adeg; k++) {
719 for (i=k-2; i>=0; i--)
720 temp = temp * (alpha[k] - alpha[i]) + v[i];
721 v.push_back((u[k] - temp) * rcp[k]);
724 // Convert from Newton form to standard form
726 for (k=adeg-1; k>=0; k--)
727 c = c * (*x - alpha[k]) + v[k];
729 if (c.degree(*x) == (adeg - bdeg)) {
737 // Polynomial long division (recursive)
743 ex blcoeff = eb.coeff(*x, bdeg);
744 while (rdeg >= bdeg) {
745 ex term, rcoeff = r.coeff(*x, rdeg);
746 if (!divide_in_z(rcoeff, blcoeff, term, var+1))
748 term = (term * power(*x, rdeg - bdeg)).expand();
750 r -= (term * eb).expand();
753 dr_remember[ex2(a, b)] = exbool(q, true);
760 dr_remember[ex2(a, b)] = exbool(q, false);
769 * Separation of unit part, content part and primitive part of polynomials
772 /** Compute unit part (= sign of leading coefficient) of a multivariate
773 * polynomial in Z[x]. The product of unit part, content part, and primitive
774 * part is the polynomial itself.
776 * @param x variable in which to compute the unit part
778 * @see ex::content, ex::primpart */
779 ex ex::unit(const symbol &x) const
781 ex c = expand().lcoeff(x);
782 if (is_ex_exactly_of_type(c, numeric))
783 return c < _ex0() ? _ex_1() : _ex1();
786 if (get_first_symbol(c, y))
789 throw(std::invalid_argument("invalid expression in unit()"));
794 /** Compute content part (= unit normal GCD of all coefficients) of a
795 * multivariate polynomial in Z[x]. The product of unit part, content part,
796 * and primitive part is the polynomial itself.
798 * @param x variable in which to compute the content part
799 * @return content part
800 * @see ex::unit, ex::primpart */
801 ex ex::content(const symbol &x) const
805 if (is_ex_exactly_of_type(*this, numeric))
806 return info(info_flags::negative) ? -*this : *this;
811 // First, try the integer content
812 ex c = e.integer_content();
814 ex lcoeff = r.lcoeff(x);
815 if (lcoeff.info(info_flags::integer))
818 // GCD of all coefficients
819 int deg = e.degree(x);
820 int ldeg = e.ldegree(x);
822 return e.lcoeff(x) / e.unit(x);
824 for (int i=ldeg; i<=deg; i++)
825 c = gcd(e.coeff(x, i), c, NULL, NULL, false);
830 /** Compute primitive part of a multivariate polynomial in Z[x].
831 * The product of unit part, content part, and primitive part is the
834 * @param x variable in which to compute the primitive part
835 * @return primitive part
836 * @see ex::unit, ex::content */
837 ex ex::primpart(const symbol &x) const
841 if (is_ex_exactly_of_type(*this, numeric))
848 if (is_ex_exactly_of_type(c, numeric))
849 return *this / (c * u);
851 return quo(*this, c * u, x, false);
855 /** Compute primitive part of a multivariate polynomial in Z[x] when the
856 * content part is already known. This function is faster in computing the
857 * primitive part than the previous function.
859 * @param x variable in which to compute the primitive part
860 * @param c previously computed content part
861 * @return primitive part */
862 ex ex::primpart(const symbol &x, const ex &c) const
868 if (is_ex_exactly_of_type(*this, numeric))
872 if (is_ex_exactly_of_type(c, numeric))
873 return *this / (c * u);
875 return quo(*this, c * u, x, false);
880 * GCD of multivariate polynomials
883 /** Compute GCD of multivariate polynomials using the Euclidean PRS algorithm
884 * (not really suited for multivariate GCDs). This function is only provided
885 * for testing purposes.
887 * @param a first multivariate polynomial
888 * @param b second multivariate polynomial
889 * @param x pointer to symbol (main variable) in which to compute the GCD in
890 * @return the GCD as a new expression
893 static ex eu_gcd(const ex &a, const ex &b, const symbol *x)
895 //clog << "eu_gcd(" << a << "," << b << ")\n";
897 // Sort c and d so that c has higher degree
899 int adeg = a.degree(*x), bdeg = b.degree(*x);
908 // Euclidean algorithm
911 //clog << " d = " << d << endl;
912 r = rem(c, d, *x, false);
914 return d.primpart(*x);
921 /** Compute GCD of multivariate polynomials using the Euclidean PRS algorithm
922 * with pseudo-remainders ("World's Worst GCD Algorithm", staying in Z[X]).
923 * This function is only provided for testing purposes.
925 * @param a first multivariate polynomial
926 * @param b second multivariate polynomial
927 * @param x pointer to symbol (main variable) in which to compute the GCD in
928 * @return the GCD as a new expression
931 static ex euprem_gcd(const ex &a, const ex &b, const symbol *x)
933 //clog << "euprem_gcd(" << a << "," << b << ")\n";
935 // Sort c and d so that c has higher degree
937 int adeg = a.degree(*x), bdeg = b.degree(*x);
946 // Euclidean algorithm with pseudo-remainders
949 //clog << " d = " << d << endl;
950 r = prem(c, d, *x, false);
952 return d.primpart(*x);
959 /** Compute GCD of multivariate polynomials using the primitive Euclidean
960 * PRS algorithm (complete content removal at each step). This function is
961 * only provided for testing purposes.
963 * @param a first multivariate polynomial
964 * @param b second multivariate polynomial
965 * @param x pointer to symbol (main variable) in which to compute the GCD in
966 * @return the GCD as a new expression
969 static ex peu_gcd(const ex &a, const ex &b, const symbol *x)
971 //clog << "peu_gcd(" << a << "," << b << ")\n";
973 // Sort c and d so that c has higher degree
975 int adeg = a.degree(*x), bdeg = b.degree(*x);
987 // Remove content from c and d, to be attached to GCD later
988 ex cont_c = c.content(*x);
989 ex cont_d = d.content(*x);
990 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
993 c = c.primpart(*x, cont_c);
994 d = d.primpart(*x, cont_d);
996 // Euclidean algorithm with content removal
999 //clog << " d = " << d << endl;
1000 r = prem(c, d, *x, false);
1009 /** Compute GCD of multivariate polynomials using the reduced PRS algorithm.
1010 * This function is only provided for testing purposes.
1012 * @param a first multivariate polynomial
1013 * @param b second multivariate polynomial
1014 * @param x pointer to symbol (main variable) in which to compute the GCD in
1015 * @return the GCD as a new expression
1018 static ex red_gcd(const ex &a, const ex &b, const symbol *x)
1020 //clog << "red_gcd(" << a << "," << b << ")\n";
1022 // Sort c and d so that c has higher degree
1024 int adeg = a.degree(*x), bdeg = b.degree(*x);
1038 // Remove content from c and d, to be attached to GCD later
1039 ex cont_c = c.content(*x);
1040 ex cont_d = d.content(*x);
1041 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1044 c = c.primpart(*x, cont_c);
1045 d = d.primpart(*x, cont_d);
1047 // First element of subresultant sequence
1049 int delta = cdeg - ddeg;
1052 // Calculate polynomial pseudo-remainder
1053 //clog << " d = " << d << endl;
1054 r = prem(c, d, *x, false);
1056 return gamma * d.primpart(*x);
1060 if (!divide(r, pow(ri, delta), d, false))
1061 throw(std::runtime_error("invalid expression in red_gcd(), division failed"));
1062 ddeg = d.degree(*x);
1064 if (is_ex_exactly_of_type(r, numeric))
1067 return gamma * r.primpart(*x);
1070 ri = c.expand().lcoeff(*x);
1071 delta = cdeg - ddeg;
1076 /** Compute GCD of multivariate polynomials using the subresultant PRS
1077 * algorithm. This function is used internally by gcd().
1079 * @param a first multivariate polynomial
1080 * @param b second multivariate polynomial
1081 * @param x pointer to symbol (main variable) in which to compute the GCD in
1082 * @return the GCD as a new expression
1084 static ex sr_gcd(const ex &a, const ex &b, const symbol *x)
1086 //clog << "sr_gcd(" << a << "," << b << ")\n";
1091 // Sort c and d so that c has higher degree
1093 int adeg = a.degree(*x), bdeg = b.degree(*x);
1107 // Remove content from c and d, to be attached to GCD later
1108 ex cont_c = c.content(*x);
1109 ex cont_d = d.content(*x);
1110 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1113 c = c.primpart(*x, cont_c);
1114 d = d.primpart(*x, cont_d);
1115 //clog << " content " << gamma << " removed, continuing with sr_gcd(" << c << "," << d << ")\n";
1117 // First element of subresultant sequence
1118 ex r = _ex0(), ri = _ex1(), psi = _ex1();
1119 int delta = cdeg - ddeg;
1122 // Calculate polynomial pseudo-remainder
1123 //clog << " start of loop, psi = " << psi << ", calculating pseudo-remainder...\n";
1124 //clog << " d = " << d << endl;
1125 r = prem(c, d, *x, false);
1127 return gamma * d.primpart(*x);
1130 //clog << " dividing...\n";
1131 if (!divide(r, ri * pow(psi, delta), d, false))
1132 throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
1133 ddeg = d.degree(*x);
1135 if (is_ex_exactly_of_type(r, numeric))
1138 return gamma * r.primpart(*x);
1141 // Next element of subresultant sequence
1142 //clog << " calculating next subresultant...\n";
1143 ri = c.expand().lcoeff(*x);
1147 divide(pow(ri, delta), pow(psi, delta-1), psi, false);
1148 delta = cdeg - ddeg;
1153 /** Return maximum (absolute value) coefficient of a polynomial.
1154 * This function is used internally by heur_gcd().
1156 * @param e expanded multivariate polynomial
1157 * @return maximum coefficient
1159 numeric ex::max_coefficient(void) const
1161 GINAC_ASSERT(bp!=0);
1162 return bp->max_coefficient();
1165 numeric basic::max_coefficient(void) const
1170 numeric numeric::max_coefficient(void) const
1175 numeric add::max_coefficient(void) const
1177 epvector::const_iterator it = seq.begin();
1178 epvector::const_iterator itend = seq.end();
1179 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1180 numeric cur_max = abs(ex_to_numeric(overall_coeff));
1181 while (it != itend) {
1183 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
1184 a = abs(ex_to_numeric(it->coeff));
1192 numeric mul::max_coefficient(void) const
1194 #ifdef DO_GINAC_ASSERT
1195 epvector::const_iterator it = seq.begin();
1196 epvector::const_iterator itend = seq.end();
1197 while (it != itend) {
1198 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
1201 #endif // def DO_GINAC_ASSERT
1202 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1203 return abs(ex_to_numeric(overall_coeff));
1207 /** Apply symmetric modular homomorphism to a multivariate polynomial.
1208 * This function is used internally by heur_gcd().
1210 * @param e expanded multivariate polynomial
1212 * @return mapped polynomial
1214 ex ex::smod(const numeric &xi) const
1216 GINAC_ASSERT(bp!=0);
1217 return bp->smod(xi);
1220 ex basic::smod(const numeric &xi) const
1225 ex numeric::smod(const numeric &xi) const
1227 #ifndef NO_NAMESPACE_GINAC
1228 return GiNaC::smod(*this, xi);
1229 #else // ndef NO_NAMESPACE_GINAC
1230 return ::smod(*this, xi);
1231 #endif // ndef NO_NAMESPACE_GINAC
1234 ex add::smod(const numeric &xi) const
1237 newseq.reserve(seq.size()+1);
1238 epvector::const_iterator it = seq.begin();
1239 epvector::const_iterator itend = seq.end();
1240 while (it != itend) {
1241 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
1242 #ifndef NO_NAMESPACE_GINAC
1243 numeric coeff = GiNaC::smod(ex_to_numeric(it->coeff), xi);
1244 #else // ndef NO_NAMESPACE_GINAC
1245 numeric coeff = ::smod(ex_to_numeric(it->coeff), xi);
1246 #endif // ndef NO_NAMESPACE_GINAC
1247 if (!coeff.is_zero())
1248 newseq.push_back(expair(it->rest, coeff));
1251 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1252 #ifndef NO_NAMESPACE_GINAC
1253 numeric coeff = GiNaC::smod(ex_to_numeric(overall_coeff), xi);
1254 #else // ndef NO_NAMESPACE_GINAC
1255 numeric coeff = ::smod(ex_to_numeric(overall_coeff), xi);
1256 #endif // ndef NO_NAMESPACE_GINAC
1257 return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
1260 ex mul::smod(const numeric &xi) const
1262 #ifdef DO_GINAC_ASSERT
1263 epvector::const_iterator it = seq.begin();
1264 epvector::const_iterator itend = seq.end();
1265 while (it != itend) {
1266 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
1269 #endif // def DO_GINAC_ASSERT
1270 mul * mulcopyp=new mul(*this);
1271 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1272 #ifndef NO_NAMESPACE_GINAC
1273 mulcopyp->overall_coeff = GiNaC::smod(ex_to_numeric(overall_coeff),xi);
1274 #else // ndef NO_NAMESPACE_GINAC
1275 mulcopyp->overall_coeff = ::smod(ex_to_numeric(overall_coeff),xi);
1276 #endif // ndef NO_NAMESPACE_GINAC
1277 mulcopyp->clearflag(status_flags::evaluated);
1278 mulcopyp->clearflag(status_flags::hash_calculated);
1279 return mulcopyp->setflag(status_flags::dynallocated);
1283 /** Exception thrown by heur_gcd() to signal failure. */
1284 class gcdheu_failed {};
1286 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1287 * get_symbol_stats() must have been called previously with the input
1288 * polynomials and an iterator to the first element of the sym_desc vector
1289 * passed in. This function is used internally by gcd().
1291 * @param a first multivariate polynomial (expanded)
1292 * @param b second multivariate polynomial (expanded)
1293 * @param ca cofactor of polynomial a (returned), NULL to suppress
1294 * calculation of cofactor
1295 * @param cb cofactor of polynomial b (returned), NULL to suppress
1296 * calculation of cofactor
1297 * @param var iterator to first element of vector of sym_desc structs
1298 * @return the GCD as a new expression
1300 * @exception gcdheu_failed() */
1301 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
1303 //clog << "heur_gcd(" << a << "," << b << ")\n";
1308 // GCD of two numeric values -> CLN
1309 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1310 numeric g = gcd(ex_to_numeric(a), ex_to_numeric(b));
1315 *ca = ex_to_numeric(a).mul(rg);
1317 *cb = ex_to_numeric(b).mul(rg);
1321 // The first symbol is our main variable
1322 const symbol *x = var->sym;
1324 // Remove integer content
1325 numeric gc = gcd(a.integer_content(), b.integer_content());
1326 numeric rgc = gc.inverse();
1329 int maxdeg = max(p.degree(*x), q.degree(*x));
1331 // Find evaluation point
1332 numeric mp = p.max_coefficient(), mq = q.max_coefficient();
1335 xi = mq * _num2() + _num2();
1337 xi = mp * _num2() + _num2();
1340 for (int t=0; t<6; t++) {
1341 if (xi.int_length() * maxdeg > 100000) {
1342 //clog << "giving up heur_gcd, xi.int_length = " << xi.int_length() << ", maxdeg = " << maxdeg << endl;
1343 throw gcdheu_failed();
1346 // Apply evaluation homomorphism and calculate GCD
1347 ex gamma = heur_gcd(p.subs(*x == xi), q.subs(*x == xi), NULL, NULL, var+1).expand();
1348 if (!is_ex_exactly_of_type(gamma, fail)) {
1350 // Reconstruct polynomial from GCD of mapped polynomials
1352 numeric rxi = xi.inverse();
1353 for (int i=0; !gamma.is_zero(); i++) {
1354 ex gi = gamma.smod(xi);
1355 g += gi * power(*x, i);
1356 gamma = (gamma - gi) * rxi;
1358 // Remove integer content
1359 g /= g.integer_content();
1361 // If the calculated polynomial divides both a and b, this is the GCD
1363 if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1365 ex lc = g.lcoeff(*x);
1366 if (is_ex_exactly_of_type(lc, numeric) && ex_to_numeric(lc).is_negative())
1373 // Next evaluation point
1374 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1376 return *new ex(fail());
1380 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1383 * @param a first multivariate polynomial
1384 * @param b second multivariate polynomial
1385 * @param check_args check whether a and b are polynomials with rational
1386 * coefficients (defaults to "true")
1387 * @return the GCD as a new expression */
1388 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1390 //clog << "gcd(" << a << "," << b << ")\n";
1395 // GCD of numerics -> CLN
1396 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1397 numeric g = gcd(ex_to_numeric(a), ex_to_numeric(b));
1399 *ca = ex_to_numeric(a) / g;
1401 *cb = ex_to_numeric(b) / g;
1406 if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)) {
1407 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1410 // Partially factored cases (to avoid expanding large expressions)
1411 if (is_ex_exactly_of_type(a, mul)) {
1412 if (is_ex_exactly_of_type(b, mul) && b.nops() > a.nops())
1418 for (unsigned i=0; i<a.nops(); i++) {
1419 ex part_ca, part_cb;
1420 g *= gcd(a.op(i), part_b, &part_ca, &part_cb, check_args);
1429 } else if (is_ex_exactly_of_type(b, mul)) {
1430 if (is_ex_exactly_of_type(a, mul) && a.nops() > b.nops())
1436 for (unsigned i=0; i<b.nops(); i++) {
1437 ex part_ca, part_cb;
1438 g *= gcd(part_a, b.op(i), &part_ca, &part_cb, check_args);
1450 // Input polynomials of the form poly^n are sometimes also trivial
1451 if (is_ex_exactly_of_type(a, power)) {
1453 if (is_ex_exactly_of_type(b, power)) {
1454 if (p.is_equal(b.op(0))) {
1455 // a = p^n, b = p^m, gcd = p^min(n, m)
1456 ex exp_a = a.op(1), exp_b = b.op(1);
1457 if (exp_a < exp_b) {
1461 *cb = power(p, exp_b - exp_a);
1462 return power(p, exp_a);
1465 *ca = power(p, exp_a - exp_b);
1468 return power(p, exp_b);
1472 if (p.is_equal(b)) {
1473 // a = p^n, b = p, gcd = p
1475 *ca = power(p, a.op(1) - 1);
1481 } else if (is_ex_exactly_of_type(b, power)) {
1483 if (p.is_equal(a)) {
1484 // a = p, b = p^n, gcd = p
1488 *cb = power(p, b.op(1) - 1);
1494 // Some trivial cases
1495 ex aex = a.expand(), bex = b.expand();
1496 if (aex.is_zero()) {
1503 if (bex.is_zero()) {
1510 if (aex.is_equal(_ex1()) || bex.is_equal(_ex1())) {
1518 if (a.is_equal(b)) {
1527 // Gather symbol statistics
1528 sym_desc_vec sym_stats;
1529 get_symbol_stats(a, b, sym_stats);
1531 // The symbol with least degree is our main variable
1532 sym_desc_vec::const_iterator var = sym_stats.begin();
1533 const symbol *x = var->sym;
1535 // Cancel trivial common factor
1536 int ldeg_a = var->ldeg_a;
1537 int ldeg_b = var->ldeg_b;
1538 int min_ldeg = min(ldeg_a, ldeg_b);
1540 ex common = power(*x, min_ldeg);
1541 //clog << "trivial common factor " << common << endl;
1542 return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1545 // Try to eliminate variables
1546 if (var->deg_a == 0) {
1547 //clog << "eliminating variable " << *x << " from b" << endl;
1548 ex c = bex.content(*x);
1549 ex g = gcd(aex, c, ca, cb, false);
1551 *cb *= bex.unit(*x) * bex.primpart(*x, c);
1553 } else if (var->deg_b == 0) {
1554 //clog << "eliminating variable " << *x << " from a" << endl;
1555 ex c = aex.content(*x);
1556 ex g = gcd(c, bex, ca, cb, false);
1558 *ca *= aex.unit(*x) * aex.primpart(*x, c);
1564 // Try heuristic algorithm first, fall back to PRS if that failed
1566 g = heur_gcd(aex, bex, ca, cb, var);
1567 } catch (gcdheu_failed) {
1568 g = *new ex(fail());
1570 if (is_ex_exactly_of_type(g, fail)) {
1571 //clog << "heuristics failed" << endl;
1576 // g = heur_gcd(aex, bex, ca, cb, var);
1577 // g = eu_gcd(aex, bex, x);
1578 // g = euprem_gcd(aex, bex, x);
1579 // g = peu_gcd(aex, bex, x);
1580 // g = red_gcd(aex, bex, x);
1581 g = sr_gcd(aex, bex, x);
1582 if (g.is_equal(_ex1())) {
1583 // Keep cofactors factored if possible
1590 divide(aex, g, *ca, false);
1592 divide(bex, g, *cb, false);
1596 if (g.is_equal(_ex1())) {
1597 // Keep cofactors factored if possible
1609 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1611 * @param a first multivariate polynomial
1612 * @param b second multivariate polynomial
1613 * @param check_args check whether a and b are polynomials with rational
1614 * coefficients (defaults to "true")
1615 * @return the LCM as a new expression */
1616 ex lcm(const ex &a, const ex &b, bool check_args)
1618 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
1619 return lcm(ex_to_numeric(a), ex_to_numeric(b));
1620 if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1621 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1624 ex g = gcd(a, b, &ca, &cb, false);
1630 * Square-free factorization
1633 // Univariate GCD of polynomials in Q[x] (used internally by sqrfree()).
1634 // a and b can be multivariate polynomials but they are treated as univariate polynomials in x.
1635 static ex univariate_gcd(const ex &a, const ex &b, const symbol &x)
1641 if (a.is_equal(_ex1()) || b.is_equal(_ex1()))
1643 if (is_ex_of_type(a, numeric) && is_ex_of_type(b, numeric))
1644 return gcd(ex_to_numeric(a), ex_to_numeric(b));
1645 if (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1646 throw(std::invalid_argument("univariate_gcd: arguments must be polynomials over the rationals"));
1648 // Euclidean algorithm
1650 if (a.degree(x) >= b.degree(x)) {
1658 r = rem(c, d, x, false);
1664 return d / d.lcoeff(x);
1668 /** Compute square-free factorization of multivariate polynomial a(x) using
1671 * @param a multivariate polynomial
1672 * @param x variable to factor in
1673 * @return factored polynomial */
1674 ex sqrfree(const ex &a, const symbol &x)
1679 ex c = univariate_gcd(a, b, x);
1681 if (c.is_equal(_ex1())) {
1685 ex y = quo(b, c, x);
1686 ex z = y - w.diff(x);
1687 while (!z.is_zero()) {
1688 ex g = univariate_gcd(w, z, x);
1696 return res * power(w, i);
1701 * Normal form of rational functions
1705 * Note: The internal normal() functions (= basic::normal() and overloaded
1706 * functions) all return lists of the form {numerator, denominator}. This
1707 * is to get around mul::eval()'s automatic expansion of numeric coefficients.
1708 * E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
1709 * the information that (a+b) is the numerator and 3 is the denominator.
1712 /** Create a symbol for replacing the expression "e" (or return a previously
1713 * assigned symbol). The symbol is appended to sym_lst and returned, the
1714 * expression is appended to repl_lst.
1715 * @see ex::normal */
1716 static ex replace_with_symbol(const ex &e, lst &sym_lst, lst &repl_lst)
1718 // Expression already in repl_lst? Then return the assigned symbol
1719 for (unsigned i=0; i<repl_lst.nops(); i++)
1720 if (repl_lst.op(i).is_equal(e))
1721 return sym_lst.op(i);
1723 // Otherwise create new symbol and add to list, taking care that the
1724 // replacement expression doesn't contain symbols from the sym_lst
1725 // because subs() is not recursive
1728 ex e_replaced = e.subs(sym_lst, repl_lst);
1730 repl_lst.append(e_replaced);
1734 /** Create a symbol for replacing the expression "e" (or return a previously
1735 * assigned symbol). An expression of the form "symbol == expression" is added
1736 * to repl_lst and the symbol is returned.
1737 * @see ex::to_rational */
1738 static ex replace_with_symbol(const ex &e, lst &repl_lst)
1740 // Expression already in repl_lst? Then return the assigned symbol
1741 for (unsigned i=0; i<repl_lst.nops(); i++)
1742 if (repl_lst.op(i).op(1).is_equal(e))
1743 return repl_lst.op(i).op(0);
1745 // Otherwise create new symbol and add to list, taking care that the
1746 // replacement expression doesn't contain symbols from the sym_lst
1747 // because subs() is not recursive
1750 ex e_replaced = e.subs(repl_lst);
1751 repl_lst.append(es == e_replaced);
1755 /** Default implementation of ex::normal(). It replaces the object with a
1757 * @see ex::normal */
1758 ex basic::normal(lst &sym_lst, lst &repl_lst, int level) const
1760 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1764 /** Implementation of ex::normal() for symbols. This returns the unmodified symbol.
1765 * @see ex::normal */
1766 ex symbol::normal(lst &sym_lst, lst &repl_lst, int level) const
1768 return (new lst(*this, _ex1()))->setflag(status_flags::dynallocated);
1772 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1773 * into re+I*im and replaces I and non-rational real numbers with a temporary
1775 * @see ex::normal */
1776 ex numeric::normal(lst &sym_lst, lst &repl_lst, int level) const
1778 numeric num = numer();
1781 if (num.is_real()) {
1782 if (!num.is_integer())
1783 numex = replace_with_symbol(numex, sym_lst, repl_lst);
1785 numeric re = num.real(), im = num.imag();
1786 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, sym_lst, repl_lst);
1787 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, sym_lst, repl_lst);
1788 numex = re_ex + im_ex * replace_with_symbol(I, sym_lst, repl_lst);
1791 // Denominator is always a real integer (see numeric::denom())
1792 return (new lst(numex, denom()))->setflag(status_flags::dynallocated);
1796 /** Fraction cancellation.
1797 * @param n numerator
1798 * @param d denominator
1799 * @return cancelled fraction {n, d} as a list */
1800 static ex frac_cancel(const ex &n, const ex &d)
1804 numeric pre_factor = _num1();
1806 //clog << "frac_cancel num = " << num << ", den = " << den << endl;
1808 // Handle special cases where numerator or denominator is 0
1810 return (new lst(_ex0(), _ex1()))->setflag(status_flags::dynallocated);
1811 if (den.expand().is_zero())
1812 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
1814 // Bring numerator and denominator to Z[X] by multiplying with
1815 // LCM of all coefficients' denominators
1816 numeric num_lcm = lcm_of_coefficients_denominators(num);
1817 numeric den_lcm = lcm_of_coefficients_denominators(den);
1818 num = multiply_lcm(num, num_lcm);
1819 den = multiply_lcm(den, den_lcm);
1820 pre_factor = den_lcm / num_lcm;
1822 // Cancel GCD from numerator and denominator
1824 if (gcd(num, den, &cnum, &cden, false) != _ex1()) {
1829 // Make denominator unit normal (i.e. coefficient of first symbol
1830 // as defined by get_first_symbol() is made positive)
1832 if (get_first_symbol(den, x)) {
1833 GINAC_ASSERT(is_ex_exactly_of_type(den.unit(*x),numeric));
1834 if (ex_to_numeric(den.unit(*x)).is_negative()) {
1840 // Return result as list
1841 //clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << endl;
1842 return (new lst(num * pre_factor.numer(), den * pre_factor.denom()))->setflag(status_flags::dynallocated);
1846 /** Implementation of ex::normal() for a sum. It expands terms and performs
1847 * fractional addition.
1848 * @see ex::normal */
1849 ex add::normal(lst &sym_lst, lst &repl_lst, int level) const
1852 return (new lst(*this, _ex1()))->setflag(status_flags::dynallocated);
1853 else if (level == -max_recursion_level)
1854 throw(std::runtime_error("max recursion level reached"));
1856 // Normalize and expand children, chop into summands
1858 o.reserve(seq.size()+1);
1859 epvector::const_iterator it = seq.begin(), itend = seq.end();
1860 while (it != itend) {
1862 // Normalize and expand child
1863 ex n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1).expand();
1865 // If numerator is a sum, chop into summands
1866 if (is_ex_exactly_of_type(n.op(0), add)) {
1867 epvector::const_iterator bit = ex_to_add(n.op(0)).seq.begin(), bitend = ex_to_add(n.op(0)).seq.end();
1868 while (bit != bitend) {
1869 o.push_back((new lst(recombine_pair_to_ex(*bit), n.op(1)))->setflag(status_flags::dynallocated));
1873 // The overall_coeff is already normalized (== rational), we just
1874 // split it into numerator and denominator
1875 GINAC_ASSERT(ex_to_numeric(ex_to_add(n.op(0)).overall_coeff).is_rational());
1876 numeric overall = ex_to_numeric(ex_to_add(n.op(0)).overall_coeff);
1877 o.push_back((new lst(overall.numer(), overall.denom() * n.op(1)))->setflag(status_flags::dynallocated));
1882 o.push_back(overall_coeff.bp->normal(sym_lst, repl_lst, level-1));
1884 // o is now a vector of {numerator, denominator} lists
1886 // Determine common denominator
1888 exvector::const_iterator ait = o.begin(), aitend = o.end();
1889 //clog << "add::normal uses the following summands:\n";
1890 while (ait != aitend) {
1891 //clog << " num = " << ait->op(0) << ", den = " << ait->op(1) << endl;
1892 den = lcm(ait->op(1), den, false);
1895 //clog << " common denominator = " << den << endl;
1898 if (den.is_equal(_ex1())) {
1900 // Common denominator is 1, simply add all numerators
1902 for (ait=o.begin(); ait!=aitend; ait++) {
1903 num_seq.push_back(ait->op(0));
1905 return (new lst((new add(num_seq))->setflag(status_flags::dynallocated), den))->setflag(status_flags::dynallocated);
1909 // Perform fractional addition
1911 for (ait=o.begin(); ait!=aitend; ait++) {
1913 if (!divide(den, ait->op(1), q, false)) {
1914 // should not happen
1915 throw(std::runtime_error("invalid expression in add::normal, division failed"));
1917 num_seq.push_back((ait->op(0) * q).expand());
1919 ex num = (new add(num_seq))->setflag(status_flags::dynallocated);
1921 // Cancel common factors from num/den
1922 return frac_cancel(num, den);
1927 /** Implementation of ex::normal() for a product. It cancels common factors
1929 * @see ex::normal() */
1930 ex mul::normal(lst &sym_lst, lst &repl_lst, int level) const
1933 return (new lst(*this, _ex1()))->setflag(status_flags::dynallocated);
1934 else if (level == -max_recursion_level)
1935 throw(std::runtime_error("max recursion level reached"));
1937 // Normalize children, separate into numerator and denominator
1941 epvector::const_iterator it = seq.begin(), itend = seq.end();
1942 while (it != itend) {
1943 n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1);
1948 n = overall_coeff.bp->normal(sym_lst, repl_lst, level-1);
1952 // Perform fraction cancellation
1953 return frac_cancel(num, den);
1957 /** Implementation of ex::normal() for powers. It normalizes the basis,
1958 * distributes integer exponents to numerator and denominator, and replaces
1959 * non-integer powers by temporary symbols.
1960 * @see ex::normal */
1961 ex power::normal(lst &sym_lst, lst &repl_lst, int level) const
1964 return (new lst(*this, _ex1()))->setflag(status_flags::dynallocated);
1965 else if (level == -max_recursion_level)
1966 throw(std::runtime_error("max recursion level reached"));
1969 ex n = basis.bp->normal(sym_lst, repl_lst, level-1);
1971 if (exponent.info(info_flags::integer)) {
1973 if (exponent.info(info_flags::positive)) {
1975 // (a/b)^n -> {a^n, b^n}
1976 return (new lst(power(n.op(0), exponent), power(n.op(1), exponent)))->setflag(status_flags::dynallocated);
1978 } else if (exponent.info(info_flags::negative)) {
1980 // (a/b)^-n -> {b^n, a^n}
1981 return (new lst(power(n.op(1), -exponent), power(n.op(0), -exponent)))->setflag(status_flags::dynallocated);
1986 if (exponent.info(info_flags::positive)) {
1988 // (a/b)^x -> {sym((a/b)^x), 1}
1989 return (new lst(replace_with_symbol(power(n.op(0) / n.op(1), exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1991 } else if (exponent.info(info_flags::negative)) {
1993 if (n.op(1).is_equal(_ex1())) {
1995 // a^-x -> {1, sym(a^x)}
1996 return (new lst(_ex1(), replace_with_symbol(power(n.op(0), -exponent), sym_lst, repl_lst)))->setflag(status_flags::dynallocated);
2000 // (a/b)^-x -> {sym((b/a)^x), 1}
2001 return (new lst(replace_with_symbol(power(n.op(1) / n.op(0), -exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
2004 } else { // exponent not numeric
2006 // (a/b)^x -> {sym((a/b)^x, 1}
2007 return (new lst(replace_with_symbol(power(n.op(0) / n.op(1), exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
2013 /** Implementation of ex::normal() for pseries. It normalizes each coefficient and
2014 * replaces the series by a temporary symbol.
2015 * @see ex::normal */
2016 ex pseries::normal(lst &sym_lst, lst &repl_lst, int level) const
2019 new_seq.reserve(seq.size());
2021 epvector::const_iterator it = seq.begin(), itend = seq.end();
2022 while (it != itend) {
2023 new_seq.push_back(expair(it->rest.normal(), it->coeff));
2026 ex n = pseries(relational(var,point), new_seq);
2027 return (new lst(replace_with_symbol(n, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
2031 /** Implementation of ex::normal() for relationals. It normalizes both sides.
2032 * @see ex::normal */
2033 ex relational::normal(lst &sym_lst, lst &repl_lst, int level) const
2035 return (new lst(relational(lh.normal(), rh.normal(), o), _ex1()))->setflag(status_flags::dynallocated);
2039 /** Normalization of rational functions.
2040 * This function converts an expression to its normal form
2041 * "numerator/denominator", where numerator and denominator are (relatively
2042 * prime) polynomials. Any subexpressions which are not rational functions
2043 * (like non-rational numbers, non-integer powers or functions like sin(),
2044 * cos() etc.) are replaced by temporary symbols which are re-substituted by
2045 * the (normalized) subexpressions before normal() returns (this way, any
2046 * expression can be treated as a rational function). normal() is applied
2047 * recursively to arguments of functions etc.
2049 * @param level maximum depth of recursion
2050 * @return normalized expression */
2051 ex ex::normal(int level) const
2053 lst sym_lst, repl_lst;
2055 ex e = bp->normal(sym_lst, repl_lst, level);
2056 GINAC_ASSERT(is_ex_of_type(e, lst));
2058 // Re-insert replaced symbols
2059 if (sym_lst.nops() > 0)
2060 e = e.subs(sym_lst, repl_lst);
2062 // Convert {numerator, denominator} form back to fraction
2063 return e.op(0) / e.op(1);
2066 /** Numerator of an expression. If the expression is not of the normal form
2067 * "numerator/denominator", it is first converted to this form and then the
2068 * numerator is returned.
2071 * @return numerator */
2072 ex ex::numer(void) const
2074 lst sym_lst, repl_lst;
2076 ex e = bp->normal(sym_lst, repl_lst, 0);
2077 GINAC_ASSERT(is_ex_of_type(e, lst));
2079 // Re-insert replaced symbols
2080 if (sym_lst.nops() > 0)
2081 return e.op(0).subs(sym_lst, repl_lst);
2086 /** Denominator of an expression. If the expression is not of the normal form
2087 * "numerator/denominator", it is first converted to this form and then the
2088 * denominator is returned.
2091 * @return denominator */
2092 ex ex::denom(void) const
2094 lst sym_lst, repl_lst;
2096 ex e = bp->normal(sym_lst, repl_lst, 0);
2097 GINAC_ASSERT(is_ex_of_type(e, lst));
2099 // Re-insert replaced symbols
2100 if (sym_lst.nops() > 0)
2101 return e.op(1).subs(sym_lst, repl_lst);
2107 /** Default implementation of ex::to_rational(). It replaces the object with a
2109 * @see ex::to_rational */
2110 ex basic::to_rational(lst &repl_lst) const
2112 return replace_with_symbol(*this, repl_lst);
2116 /** Implementation of ex::to_rational() for symbols. This returns the
2117 * unmodified symbol.
2118 * @see ex::to_rational */
2119 ex symbol::to_rational(lst &repl_lst) const
2125 /** Implementation of ex::to_rational() for a numeric. It splits complex
2126 * numbers into re+I*im and replaces I and non-rational real numbers with a
2128 * @see ex::to_rational */
2129 ex numeric::to_rational(lst &repl_lst) const
2133 return replace_with_symbol(*this, repl_lst);
2135 numeric re = real();
2136 numeric im = imag();
2137 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl_lst);
2138 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl_lst);
2139 return re_ex + im_ex * replace_with_symbol(I, repl_lst);
2145 /** Implementation of ex::to_rational() for powers. It replaces non-integer
2146 * powers by temporary symbols.
2147 * @see ex::to_rational */
2148 ex power::to_rational(lst &repl_lst) const
2150 if (exponent.info(info_flags::integer))
2151 return power(basis.to_rational(repl_lst), exponent);
2153 return replace_with_symbol(*this, repl_lst);
2157 /** Implementation of ex::to_rational() for expairseqs.
2158 * @see ex::to_rational */
2159 ex expairseq::to_rational(lst &repl_lst) const
2162 s.reserve(seq.size());
2163 for (epvector::const_iterator it=seq.begin(); it!=seq.end(); ++it) {
2164 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*it).to_rational(repl_lst)));
2165 // s.push_back(combine_ex_with_coeff_to_pair((*it).rest.to_rational(repl_lst),
2167 ex oc = overall_coeff.to_rational(repl_lst);
2168 if (oc.info(info_flags::numeric))
2169 return thisexpairseq(s, overall_coeff);
2170 else s.push_back(combine_ex_with_coeff_to_pair(oc,_ex1()));
2171 return thisexpairseq(s, default_overall_coeff());
2175 /** Rationalization of non-rational functions.
2176 * This function converts a general expression to a rational polynomial
2177 * by replacing all non-rational subexpressions (like non-rational numbers,
2178 * non-integer powers or functions like sin(), cos() etc.) to temporary
2179 * symbols. This makes it possible to use functions like gcd() and divide()
2180 * on non-rational functions by applying to_rational() on the arguments,
2181 * calling the desired function and re-substituting the temporary symbols
2182 * in the result. To make the last step possible, all temporary symbols and
2183 * their associated expressions are collected in the list specified by the
2184 * repl_lst parameter in the form {symbol == expression}, ready to be passed
2185 * as an argument to ex::subs().
2187 * @param repl_lst collects a list of all temporary symbols and their replacements
2188 * @return rationalized expression */
2189 ex ex::to_rational(lst &repl_lst) const
2191 return bp->to_rational(repl_lst);
2195 #ifndef NO_NAMESPACE_GINAC
2196 } // namespace GiNaC
2197 #endif // ndef NO_NAMESPACE_GINAC