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-2001 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 (always slower except for completely dense
64 #define USE_TRIAL_DIVISION 0
66 // Set this to enable some statistical output for the GCD routines
71 // Statistics variables
72 static int gcd_called = 0;
73 static int sr_gcd_called = 0;
74 static int heur_gcd_called = 0;
75 static int heur_gcd_failed = 0;
77 // Print statistics at end of program
78 static struct _stat_print {
81 cout << "gcd() called " << gcd_called << " times\n";
82 cout << "sr_gcd() called " << sr_gcd_called << " times\n";
83 cout << "heur_gcd() called " << heur_gcd_called << " times\n";
84 cout << "heur_gcd() failed " << heur_gcd_failed << " times\n";
90 /** Return pointer to first symbol found in expression. Due to GiNaCĀ“s
91 * internal ordering of terms, it may not be obvious which symbol this
92 * function returns for a given expression.
94 * @param e expression to search
95 * @param x pointer to first symbol found (returned)
96 * @return "false" if no symbol was found, "true" otherwise */
97 static bool get_first_symbol(const ex &e, const symbol *&x)
99 if (is_ex_exactly_of_type(e, symbol)) {
100 x = static_cast<symbol *>(e.bp);
102 } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
103 for (unsigned i=0; i<e.nops(); i++)
104 if (get_first_symbol(e.op(i), x))
106 } else if (is_ex_exactly_of_type(e, power)) {
107 if (get_first_symbol(e.op(0), x))
115 * Statistical information about symbols in polynomials
118 /** This structure holds information about the highest and lowest degrees
119 * in which a symbol appears in two multivariate polynomials "a" and "b".
120 * A vector of these structures with information about all symbols in
121 * two polynomials can be created with the function get_symbol_stats().
123 * @see get_symbol_stats */
125 /** Pointer to symbol */
128 /** Highest degree of symbol in polynomial "a" */
131 /** Highest degree of symbol in polynomial "b" */
134 /** Lowest degree of symbol in polynomial "a" */
137 /** Lowest degree of symbol in polynomial "b" */
140 /** Maximum of deg_a and deg_b (Used for sorting) */
143 /** Commparison operator for sorting */
144 bool operator<(const sym_desc &x) const {return max_deg < x.max_deg;}
147 // Vector of sym_desc structures
148 typedef std::vector<sym_desc> sym_desc_vec;
150 // Add symbol the sym_desc_vec (used internally by get_symbol_stats())
151 static void add_symbol(const symbol *s, sym_desc_vec &v)
153 sym_desc_vec::iterator it = v.begin(), itend = v.end();
154 while (it != itend) {
155 if (it->sym->compare(*s) == 0) // If it's already in there, don't add it a second time
164 // Collect all symbols of an expression (used internally by get_symbol_stats())
165 static void collect_symbols(const ex &e, sym_desc_vec &v)
167 if (is_ex_exactly_of_type(e, symbol)) {
168 add_symbol(static_cast<symbol *>(e.bp), v);
169 } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
170 for (unsigned i=0; i<e.nops(); i++)
171 collect_symbols(e.op(i), v);
172 } else if (is_ex_exactly_of_type(e, power)) {
173 collect_symbols(e.op(0), v);
177 /** Collect statistical information about symbols in polynomials.
178 * This function fills in a vector of "sym_desc" structs which contain
179 * information about the highest and lowest degrees of all symbols that
180 * appear in two polynomials. The vector is then sorted by minimum
181 * degree (lowest to highest). The information gathered by this
182 * function is used by the GCD routines to identify trivial factors
183 * and to determine which variable to choose as the main variable
184 * for GCD computation.
186 * @param a first multivariate polynomial
187 * @param b second multivariate polynomial
188 * @param v vector of sym_desc structs (filled in) */
189 static void get_symbol_stats(const ex &a, const ex &b, sym_desc_vec &v)
191 collect_symbols(a.eval(), v); // eval() to expand assigned symbols
192 collect_symbols(b.eval(), v);
193 sym_desc_vec::iterator it = v.begin(), itend = v.end();
194 while (it != itend) {
195 int deg_a = a.degree(*(it->sym));
196 int deg_b = b.degree(*(it->sym));
199 it->max_deg = std::max(deg_a,deg_b);
200 it->ldeg_a = a.ldegree(*(it->sym));
201 it->ldeg_b = b.ldegree(*(it->sym));
204 sort(v.begin(), v.end());
206 std::clog << "Symbols:\n";
207 it = v.begin(); itend = v.end();
208 while (it != itend) {
209 std::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;
210 std::clog << " lcoeff_a=" << a.lcoeff(*(it->sym)) << ", lcoeff_b=" << b.lcoeff(*(it->sym)) << endl;
218 * Computation of LCM of denominators of coefficients of a polynomial
221 // Compute LCM of denominators of coefficients by going through the
222 // expression recursively (used internally by lcm_of_coefficients_denominators())
223 static numeric lcmcoeff(const ex &e, const numeric &l)
225 if (e.info(info_flags::rational))
226 return lcm(ex_to_numeric(e).denom(), l);
227 else if (is_ex_exactly_of_type(e, add)) {
229 for (unsigned i=0; i<e.nops(); i++)
230 c = lcmcoeff(e.op(i), c);
232 } else if (is_ex_exactly_of_type(e, mul)) {
234 for (unsigned i=0; i<e.nops(); i++)
235 c *= lcmcoeff(e.op(i), _num1());
237 } else if (is_ex_exactly_of_type(e, power))
238 return pow(lcmcoeff(e.op(0), l), ex_to_numeric(e.op(1)));
242 /** Compute LCM of denominators of coefficients of a polynomial.
243 * Given a polynomial with rational coefficients, this function computes
244 * the LCM of the denominators of all coefficients. This can be used
245 * to bring a polynomial from Q[X] to Z[X].
247 * @param e multivariate polynomial (need not be expanded)
248 * @return LCM of denominators of coefficients */
249 static numeric lcm_of_coefficients_denominators(const ex &e)
251 return lcmcoeff(e, _num1());
254 /** Bring polynomial from Q[X] to Z[X] by multiplying in the previously
255 * determined LCM of the coefficient's denominators.
257 * @param e multivariate polynomial (need not be expanded)
258 * @param lcm LCM to multiply in */
259 static ex multiply_lcm(const ex &e, const numeric &lcm)
261 if (is_ex_exactly_of_type(e, mul)) {
263 numeric lcm_accum = _num1();
264 for (unsigned i=0; i<e.nops(); i++) {
265 numeric op_lcm = lcmcoeff(e.op(i), _num1());
266 c *= multiply_lcm(e.op(i), op_lcm);
269 c *= lcm / lcm_accum;
271 } else if (is_ex_exactly_of_type(e, add)) {
273 for (unsigned i=0; i<e.nops(); i++)
274 c += multiply_lcm(e.op(i), lcm);
276 } else if (is_ex_exactly_of_type(e, power)) {
277 return pow(multiply_lcm(e.op(0), lcm.power(ex_to_numeric(e.op(1)).inverse())), e.op(1));
283 /** Compute the integer content (= GCD of all numeric coefficients) of an
284 * expanded polynomial.
286 * @param e expanded polynomial
287 * @return integer content */
288 numeric ex::integer_content(void) const
291 return bp->integer_content();
294 numeric basic::integer_content(void) const
299 numeric numeric::integer_content(void) const
304 numeric add::integer_content(void) const
306 epvector::const_iterator it = seq.begin();
307 epvector::const_iterator itend = seq.end();
309 while (it != itend) {
310 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
311 GINAC_ASSERT(is_ex_exactly_of_type(it->coeff,numeric));
312 c = gcd(ex_to_numeric(it->coeff), c);
315 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
316 c = gcd(ex_to_numeric(overall_coeff),c);
320 numeric mul::integer_content(void) const
322 #ifdef DO_GINAC_ASSERT
323 epvector::const_iterator it = seq.begin();
324 epvector::const_iterator itend = seq.end();
325 while (it != itend) {
326 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
329 #endif // def DO_GINAC_ASSERT
330 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
331 return abs(ex_to_numeric(overall_coeff));
336 * Polynomial quotients and remainders
339 /** Quotient q(x) of polynomials a(x) and b(x) in Q[x].
340 * It satisfies a(x)=b(x)*q(x)+r(x).
342 * @param a first polynomial in x (dividend)
343 * @param b second polynomial in x (divisor)
344 * @param x a and b are polynomials in x
345 * @param check_args check whether a and b are polynomials with rational
346 * coefficients (defaults to "true")
347 * @return quotient of a and b in Q[x] */
348 ex quo(const ex &a, const ex &b, const symbol &x, bool check_args)
351 throw(std::overflow_error("quo: division by zero"));
352 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
358 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
359 throw(std::invalid_argument("quo: arguments must be polynomials over the rationals"));
361 // Polynomial long division
366 int bdeg = b.degree(x);
367 int rdeg = r.degree(x);
368 ex blcoeff = b.expand().coeff(x, bdeg);
369 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
370 while (rdeg >= bdeg) {
371 ex term, rcoeff = r.coeff(x, rdeg);
372 if (blcoeff_is_numeric)
373 term = rcoeff / blcoeff;
375 if (!divide(rcoeff, blcoeff, term, false))
376 return *new ex(fail());
378 term *= power(x, rdeg - bdeg);
380 r -= (term * b).expand();
389 /** Remainder r(x) of polynomials a(x) and b(x) in Q[x].
390 * It satisfies a(x)=b(x)*q(x)+r(x).
392 * @param a first polynomial in x (dividend)
393 * @param b second polynomial in x (divisor)
394 * @param x a and b are polynomials in x
395 * @param check_args check whether a and b are polynomials with rational
396 * coefficients (defaults to "true")
397 * @return remainder of a(x) and b(x) in Q[x] */
398 ex rem(const ex &a, const ex &b, const symbol &x, bool check_args)
401 throw(std::overflow_error("rem: division by zero"));
402 if (is_ex_exactly_of_type(a, numeric)) {
403 if (is_ex_exactly_of_type(b, numeric))
412 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
413 throw(std::invalid_argument("rem: arguments must be polynomials over the rationals"));
415 // Polynomial long division
419 int bdeg = b.degree(x);
420 int rdeg = r.degree(x);
421 ex blcoeff = b.expand().coeff(x, bdeg);
422 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
423 while (rdeg >= bdeg) {
424 ex term, rcoeff = r.coeff(x, rdeg);
425 if (blcoeff_is_numeric)
426 term = rcoeff / blcoeff;
428 if (!divide(rcoeff, blcoeff, term, false))
429 return *new ex(fail());
431 term *= power(x, rdeg - bdeg);
432 r -= (term * b).expand();
441 /** Pseudo-remainder of polynomials a(x) and b(x) in Z[x].
443 * @param a first polynomial in x (dividend)
444 * @param b second polynomial in x (divisor)
445 * @param x a and b are polynomials in x
446 * @param check_args check whether a and b are polynomials with rational
447 * coefficients (defaults to "true")
448 * @return pseudo-remainder of a(x) and b(x) in Z[x] */
449 ex prem(const ex &a, const ex &b, const symbol &x, bool check_args)
452 throw(std::overflow_error("prem: division by zero"));
453 if (is_ex_exactly_of_type(a, numeric)) {
454 if (is_ex_exactly_of_type(b, numeric))
459 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
460 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
462 // Polynomial long division
465 int rdeg = r.degree(x);
466 int bdeg = eb.degree(x);
469 blcoeff = eb.coeff(x, bdeg);
473 eb -= blcoeff * power(x, bdeg);
477 int delta = rdeg - bdeg + 1, i = 0;
478 while (rdeg >= bdeg && !r.is_zero()) {
479 ex rlcoeff = r.coeff(x, rdeg);
480 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
484 r -= rlcoeff * power(x, rdeg);
485 r = (blcoeff * r).expand() - term;
489 return power(blcoeff, delta - i) * r;
493 /** Sparse pseudo-remainder of polynomials a(x) and b(x) in Z[x].
495 * @param a first polynomial in x (dividend)
496 * @param b second polynomial in x (divisor)
497 * @param x a and b are polynomials in x
498 * @param check_args check whether a and b are polynomials with rational
499 * coefficients (defaults to "true")
500 * @return sparse pseudo-remainder of a(x) and b(x) in Z[x] */
502 ex sprem(const ex &a, const ex &b, const symbol &x, bool check_args)
505 throw(std::overflow_error("prem: division by zero"));
506 if (is_ex_exactly_of_type(a, numeric)) {
507 if (is_ex_exactly_of_type(b, numeric))
512 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
513 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
515 // Polynomial long division
518 int rdeg = r.degree(x);
519 int bdeg = eb.degree(x);
522 blcoeff = eb.coeff(x, bdeg);
526 eb -= blcoeff * power(x, bdeg);
530 while (rdeg >= bdeg && !r.is_zero()) {
531 ex rlcoeff = r.coeff(x, rdeg);
532 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
536 r -= rlcoeff * power(x, rdeg);
537 r = (blcoeff * r).expand() - term;
544 /** Exact polynomial division of a(X) by b(X) in Q[X].
546 * @param a first multivariate polynomial (dividend)
547 * @param b second multivariate polynomial (divisor)
548 * @param q quotient (returned)
549 * @param check_args check whether a and b are polynomials with rational
550 * coefficients (defaults to "true")
551 * @return "true" when exact division succeeds (quotient returned in q),
552 * "false" otherwise */
553 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
557 throw(std::overflow_error("divide: division by zero"));
560 if (is_ex_exactly_of_type(b, numeric)) {
563 } else if (is_ex_exactly_of_type(a, numeric))
571 if (check_args && (!a.info(info_flags::rational_polynomial) ||
572 !b.info(info_flags::rational_polynomial)))
573 throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
577 if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
578 throw(std::invalid_argument("invalid expression in divide()"));
580 // Polynomial long division (recursive)
584 int bdeg = b.degree(*x);
585 int rdeg = r.degree(*x);
586 ex blcoeff = b.expand().coeff(*x, bdeg);
587 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
588 while (rdeg >= bdeg) {
589 ex term, rcoeff = r.coeff(*x, rdeg);
590 if (blcoeff_is_numeric)
591 term = rcoeff / blcoeff;
593 if (!divide(rcoeff, blcoeff, term, false))
595 term *= power(*x, rdeg - bdeg);
597 r -= (term * b).expand();
611 typedef std::pair<ex, ex> ex2;
612 typedef std::pair<ex, bool> exbool;
615 bool operator() (const ex2 p, const ex2 q) const
617 return p.first.compare(q.first) < 0 || (!(q.first.compare(p.first) < 0) && p.second.compare(q.second) < 0);
621 typedef std::map<ex2, exbool, ex2_less> ex2_exbool_remember;
625 /** Exact polynomial division of a(X) by b(X) in Z[X].
626 * This functions works like divide() but the input and output polynomials are
627 * in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
628 * divide(), it doesnĀ“t check whether the input polynomials really are integer
629 * polynomials, so be careful of what you pass in. Also, you have to run
630 * get_symbol_stats() over the input polynomials before calling this function
631 * and pass an iterator to the first element of the sym_desc vector. This
632 * function is used internally by the heur_gcd().
634 * @param a first multivariate polynomial (dividend)
635 * @param b second multivariate polynomial (divisor)
636 * @param q quotient (returned)
637 * @param var iterator to first element of vector of sym_desc structs
638 * @return "true" when exact division succeeds (the quotient is returned in
639 * q), "false" otherwise.
640 * @see get_symbol_stats, heur_gcd */
641 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
645 throw(std::overflow_error("divide_in_z: division by zero"));
646 if (b.is_equal(_ex1())) {
650 if (is_ex_exactly_of_type(a, numeric)) {
651 if (is_ex_exactly_of_type(b, numeric)) {
653 return q.info(info_flags::integer);
666 static ex2_exbool_remember dr_remember;
667 ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
668 if (remembered != dr_remember.end()) {
669 q = remembered->second.first;
670 return remembered->second.second;
675 const symbol *x = var->sym;
678 int adeg = a.degree(*x), bdeg = b.degree(*x);
682 #if USE_TRIAL_DIVISION
684 // Trial division with polynomial interpolation
687 // Compute values at evaluation points 0..adeg
688 vector<numeric> alpha; alpha.reserve(adeg + 1);
689 exvector u; u.reserve(adeg + 1);
690 numeric point = _num0();
692 for (i=0; i<=adeg; i++) {
693 ex bs = b.subs(*x == point);
694 while (bs.is_zero()) {
696 bs = b.subs(*x == point);
698 if (!divide_in_z(a.subs(*x == point), bs, c, var+1))
700 alpha.push_back(point);
706 vector<numeric> rcp; rcp.reserve(adeg + 1);
707 rcp.push_back(_num0());
708 for (k=1; k<=adeg; k++) {
709 numeric product = alpha[k] - alpha[0];
711 product *= alpha[k] - alpha[i];
712 rcp.push_back(product.inverse());
715 // Compute Newton coefficients
716 exvector v; v.reserve(adeg + 1);
718 for (k=1; k<=adeg; k++) {
720 for (i=k-2; i>=0; i--)
721 temp = temp * (alpha[k] - alpha[i]) + v[i];
722 v.push_back((u[k] - temp) * rcp[k]);
725 // Convert from Newton form to standard form
727 for (k=adeg-1; k>=0; k--)
728 c = c * (*x - alpha[k]) + v[k];
730 if (c.degree(*x) == (adeg - bdeg)) {
738 // Polynomial long division (recursive)
744 ex blcoeff = eb.coeff(*x, bdeg);
745 while (rdeg >= bdeg) {
746 ex term, rcoeff = r.coeff(*x, rdeg);
747 if (!divide_in_z(rcoeff, blcoeff, term, var+1))
749 term = (term * power(*x, rdeg - bdeg)).expand();
751 r -= (term * eb).expand();
754 dr_remember[ex2(a, b)] = exbool(q, true);
761 dr_remember[ex2(a, b)] = exbool(q, false);
770 * Separation of unit part, content part and primitive part of polynomials
773 /** Compute unit part (= sign of leading coefficient) of a multivariate
774 * polynomial in Z[x]. The product of unit part, content part, and primitive
775 * part is the polynomial itself.
777 * @param x variable in which to compute the unit part
779 * @see ex::content, ex::primpart */
780 ex ex::unit(const symbol &x) const
782 ex c = expand().lcoeff(x);
783 if (is_ex_exactly_of_type(c, numeric))
784 return c < _ex0() ? _ex_1() : _ex1();
787 if (get_first_symbol(c, y))
790 throw(std::invalid_argument("invalid expression in unit()"));
795 /** Compute content part (= unit normal GCD of all coefficients) of a
796 * multivariate polynomial in Z[x]. The product of unit part, content part,
797 * and primitive part is the polynomial itself.
799 * @param x variable in which to compute the content part
800 * @return content part
801 * @see ex::unit, ex::primpart */
802 ex ex::content(const symbol &x) const
806 if (is_ex_exactly_of_type(*this, numeric))
807 return info(info_flags::negative) ? -*this : *this;
812 // First, try the integer content
813 ex c = e.integer_content();
815 ex lcoeff = r.lcoeff(x);
816 if (lcoeff.info(info_flags::integer))
819 // GCD of all coefficients
820 int deg = e.degree(x);
821 int ldeg = e.ldegree(x);
823 return e.lcoeff(x) / e.unit(x);
825 for (int i=ldeg; i<=deg; i++)
826 c = gcd(e.coeff(x, i), c, NULL, NULL, false);
831 /** Compute primitive part of a multivariate polynomial in Z[x].
832 * The product of unit part, content part, and primitive part is the
835 * @param x variable in which to compute the primitive part
836 * @return primitive part
837 * @see ex::unit, ex::content */
838 ex ex::primpart(const symbol &x) const
842 if (is_ex_exactly_of_type(*this, numeric))
849 if (is_ex_exactly_of_type(c, numeric))
850 return *this / (c * u);
852 return quo(*this, c * u, x, false);
856 /** Compute primitive part of a multivariate polynomial in Z[x] when the
857 * content part is already known. This function is faster in computing the
858 * primitive part than the previous function.
860 * @param x variable in which to compute the primitive part
861 * @param c previously computed content part
862 * @return primitive part */
863 ex ex::primpart(const symbol &x, const ex &c) const
869 if (is_ex_exactly_of_type(*this, numeric))
873 if (is_ex_exactly_of_type(c, numeric))
874 return *this / (c * u);
876 return quo(*this, c * u, x, false);
881 * GCD of multivariate polynomials
884 /** Compute GCD of polynomials in Q[X] using the Euclidean algorithm (not
885 * really suited for multivariate GCDs). This function is only provided for
888 * @param a first multivariate polynomial
889 * @param b second multivariate polynomial
890 * @param x pointer to symbol (main variable) in which to compute the GCD in
891 * @return the GCD as a new expression
894 static ex eu_gcd(const ex &a, const ex &b, const symbol *x)
896 //std::clog << "eu_gcd(" << a << "," << b << ")\n";
898 // Sort c and d so that c has higher degree
900 int adeg = a.degree(*x), bdeg = b.degree(*x);
910 c = c / c.lcoeff(*x);
911 d = d / d.lcoeff(*x);
913 // Euclidean algorithm
916 //std::clog << " d = " << d << endl;
917 r = rem(c, d, *x, false);
919 return d / d.lcoeff(*x);
926 /** Compute GCD of multivariate polynomials using the Euclidean PRS algorithm
927 * with pseudo-remainders ("World's Worst GCD Algorithm", staying in Z[X]).
928 * This function is only provided for testing purposes.
930 * @param a first multivariate polynomial
931 * @param b second multivariate polynomial
932 * @param x pointer to symbol (main variable) in which to compute the GCD in
933 * @return the GCD as a new expression
936 static ex euprem_gcd(const ex &a, const ex &b, const symbol *x)
938 //std::clog << "euprem_gcd(" << a << "," << b << ")\n";
940 // Sort c and d so that c has higher degree
942 int adeg = a.degree(*x), bdeg = b.degree(*x);
951 // Calculate GCD of contents
952 ex gamma = gcd(c.content(*x), d.content(*x), NULL, NULL, false);
954 // Euclidean algorithm with pseudo-remainders
957 //std::clog << " d = " << d << endl;
958 r = prem(c, d, *x, false);
960 return d.primpart(*x) * gamma;
967 /** Compute GCD of multivariate polynomials using the primitive Euclidean
968 * PRS algorithm (complete content removal at each step). This function is
969 * only provided for testing purposes.
971 * @param a first multivariate polynomial
972 * @param b second multivariate polynomial
973 * @param x pointer to symbol (main variable) in which to compute the GCD in
974 * @return the GCD as a new expression
977 static ex peu_gcd(const ex &a, const ex &b, const symbol *x)
979 //std::clog << "peu_gcd(" << a << "," << b << ")\n";
981 // Sort c and d so that c has higher degree
983 int adeg = a.degree(*x), bdeg = b.degree(*x);
995 // Remove content from c and d, to be attached to GCD later
996 ex cont_c = c.content(*x);
997 ex cont_d = d.content(*x);
998 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1001 c = c.primpart(*x, cont_c);
1002 d = d.primpart(*x, cont_d);
1004 // Euclidean algorithm with content removal
1007 //std::clog << " d = " << d << endl;
1008 r = prem(c, d, *x, false);
1017 /** Compute GCD of multivariate polynomials using the reduced PRS algorithm.
1018 * This function is only provided for testing purposes.
1020 * @param a first multivariate polynomial
1021 * @param b second multivariate polynomial
1022 * @param x pointer to symbol (main variable) in which to compute the GCD in
1023 * @return the GCD as a new expression
1026 static ex red_gcd(const ex &a, const ex &b, const symbol *x)
1028 //std::clog << "red_gcd(" << a << "," << b << ")\n";
1030 // Sort c and d so that c has higher degree
1032 int adeg = a.degree(*x), bdeg = b.degree(*x);
1046 // Remove content from c and d, to be attached to GCD later
1047 ex cont_c = c.content(*x);
1048 ex cont_d = d.content(*x);
1049 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1052 c = c.primpart(*x, cont_c);
1053 d = d.primpart(*x, cont_d);
1055 // First element of divisor sequence
1057 int delta = cdeg - ddeg;
1060 // Calculate polynomial pseudo-remainder
1061 //std::clog << " d = " << d << endl;
1062 r = prem(c, d, *x, false);
1064 return gamma * d.primpart(*x);
1068 if (!divide(r, pow(ri, delta), d, false))
1069 throw(std::runtime_error("invalid expression in red_gcd(), division failed"));
1070 ddeg = d.degree(*x);
1072 if (is_ex_exactly_of_type(r, numeric))
1075 return gamma * r.primpart(*x);
1078 ri = c.expand().lcoeff(*x);
1079 delta = cdeg - ddeg;
1084 /** Compute GCD of multivariate polynomials using the subresultant PRS
1085 * algorithm. This function is used internally by gcd().
1087 * @param a first multivariate polynomial
1088 * @param b second multivariate polynomial
1089 * @param var iterator to first element of vector of sym_desc structs
1090 * @return the GCD as a new expression
1093 static ex sr_gcd(const ex &a, const ex &b, sym_desc_vec::const_iterator var)
1095 //std::clog << "sr_gcd(" << a << "," << b << ")\n";
1100 // The first symbol is our main variable
1101 const symbol &x = *(var->sym);
1103 // Sort c and d so that c has higher degree
1105 int adeg = a.degree(x), bdeg = b.degree(x);
1119 // Remove content from c and d, to be attached to GCD later
1120 ex cont_c = c.content(x);
1121 ex cont_d = d.content(x);
1122 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1125 c = c.primpart(x, cont_c);
1126 d = d.primpart(x, cont_d);
1127 //std::clog << " content " << gamma << " removed, continuing with sr_gcd(" << c << "," << d << ")\n";
1129 // First element of subresultant sequence
1130 ex r = _ex0(), ri = _ex1(), psi = _ex1();
1131 int delta = cdeg - ddeg;
1134 // Calculate polynomial pseudo-remainder
1135 //std::clog << " start of loop, psi = " << psi << ", calculating pseudo-remainder...\n";
1136 //std::clog << " d = " << d << endl;
1137 r = prem(c, d, x, false);
1139 return gamma * d.primpart(x);
1142 //std::clog << " dividing...\n";
1143 if (!divide_in_z(r, ri * pow(psi, delta), d, var))
1144 throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
1147 if (is_ex_exactly_of_type(r, numeric))
1150 return gamma * r.primpart(x);
1153 // Next element of subresultant sequence
1154 //std::clog << " calculating next subresultant...\n";
1155 ri = c.expand().lcoeff(x);
1159 divide_in_z(pow(ri, delta), pow(psi, delta-1), psi, var+1);
1160 delta = cdeg - ddeg;
1165 /** Return maximum (absolute value) coefficient of a polynomial.
1166 * This function is used internally by heur_gcd().
1168 * @param e expanded multivariate polynomial
1169 * @return maximum coefficient
1171 numeric ex::max_coefficient(void) const
1173 GINAC_ASSERT(bp!=0);
1174 return bp->max_coefficient();
1177 numeric basic::max_coefficient(void) const
1182 numeric numeric::max_coefficient(void) const
1187 numeric add::max_coefficient(void) const
1189 epvector::const_iterator it = seq.begin();
1190 epvector::const_iterator itend = seq.end();
1191 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1192 numeric cur_max = abs(ex_to_numeric(overall_coeff));
1193 while (it != itend) {
1195 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
1196 a = abs(ex_to_numeric(it->coeff));
1204 numeric mul::max_coefficient(void) const
1206 #ifdef DO_GINAC_ASSERT
1207 epvector::const_iterator it = seq.begin();
1208 epvector::const_iterator itend = seq.end();
1209 while (it != itend) {
1210 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
1213 #endif // def DO_GINAC_ASSERT
1214 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1215 return abs(ex_to_numeric(overall_coeff));
1219 /** Apply symmetric modular homomorphism to a multivariate polynomial.
1220 * This function is used internally by heur_gcd().
1222 * @param e expanded multivariate polynomial
1224 * @return mapped polynomial
1226 ex ex::smod(const numeric &xi) const
1228 GINAC_ASSERT(bp!=0);
1229 return bp->smod(xi);
1232 ex basic::smod(const numeric &xi) const
1237 ex numeric::smod(const numeric &xi) const
1239 #ifndef NO_NAMESPACE_GINAC
1240 return GiNaC::smod(*this, xi);
1241 #else // ndef NO_NAMESPACE_GINAC
1242 return ::smod(*this, xi);
1243 #endif // ndef NO_NAMESPACE_GINAC
1246 ex add::smod(const numeric &xi) const
1249 newseq.reserve(seq.size()+1);
1250 epvector::const_iterator it = seq.begin();
1251 epvector::const_iterator itend = seq.end();
1252 while (it != itend) {
1253 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
1254 #ifndef NO_NAMESPACE_GINAC
1255 numeric coeff = GiNaC::smod(ex_to_numeric(it->coeff), xi);
1256 #else // ndef NO_NAMESPACE_GINAC
1257 numeric coeff = ::smod(ex_to_numeric(it->coeff), xi);
1258 #endif // ndef NO_NAMESPACE_GINAC
1259 if (!coeff.is_zero())
1260 newseq.push_back(expair(it->rest, coeff));
1263 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1264 #ifndef NO_NAMESPACE_GINAC
1265 numeric coeff = GiNaC::smod(ex_to_numeric(overall_coeff), xi);
1266 #else // ndef NO_NAMESPACE_GINAC
1267 numeric coeff = ::smod(ex_to_numeric(overall_coeff), xi);
1268 #endif // ndef NO_NAMESPACE_GINAC
1269 return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
1272 ex mul::smod(const numeric &xi) const
1274 #ifdef DO_GINAC_ASSERT
1275 epvector::const_iterator it = seq.begin();
1276 epvector::const_iterator itend = seq.end();
1277 while (it != itend) {
1278 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
1281 #endif // def DO_GINAC_ASSERT
1282 mul * mulcopyp=new mul(*this);
1283 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1284 #ifndef NO_NAMESPACE_GINAC
1285 mulcopyp->overall_coeff = GiNaC::smod(ex_to_numeric(overall_coeff),xi);
1286 #else // ndef NO_NAMESPACE_GINAC
1287 mulcopyp->overall_coeff = ::smod(ex_to_numeric(overall_coeff),xi);
1288 #endif // ndef NO_NAMESPACE_GINAC
1289 mulcopyp->clearflag(status_flags::evaluated);
1290 mulcopyp->clearflag(status_flags::hash_calculated);
1291 return mulcopyp->setflag(status_flags::dynallocated);
1295 /** xi-adic polynomial interpolation */
1296 static ex interpolate(const ex &gamma, const numeric &xi, const symbol &x)
1300 numeric rxi = xi.inverse();
1301 for (int i=0; !e.is_zero(); i++) {
1303 g += gi * power(x, i);
1309 /** Exception thrown by heur_gcd() to signal failure. */
1310 class gcdheu_failed {};
1312 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1313 * get_symbol_stats() must have been called previously with the input
1314 * polynomials and an iterator to the first element of the sym_desc vector
1315 * passed in. This function is used internally by gcd().
1317 * @param a first multivariate polynomial (expanded)
1318 * @param b second multivariate polynomial (expanded)
1319 * @param ca cofactor of polynomial a (returned), NULL to suppress
1320 * calculation of cofactor
1321 * @param cb cofactor of polynomial b (returned), NULL to suppress
1322 * calculation of cofactor
1323 * @param var iterator to first element of vector of sym_desc structs
1324 * @return the GCD as a new expression
1326 * @exception gcdheu_failed() */
1327 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
1329 //std::clog << "heur_gcd(" << a << "," << b << ")\n";
1334 // Algorithms only works for non-vanishing input polynomials
1335 if (a.is_zero() || b.is_zero())
1336 return *new ex(fail());
1338 // GCD of two numeric values -> CLN
1339 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1340 numeric g = gcd(ex_to_numeric(a), ex_to_numeric(b));
1342 *ca = ex_to_numeric(a) / g;
1344 *cb = ex_to_numeric(b) / g;
1348 // The first symbol is our main variable
1349 const symbol &x = *(var->sym);
1351 // Remove integer content
1352 numeric gc = gcd(a.integer_content(), b.integer_content());
1353 numeric rgc = gc.inverse();
1356 int maxdeg = std::max(p.degree(x),q.degree(x));
1358 // Find evaluation point
1359 numeric mp = p.max_coefficient();
1360 numeric mq = q.max_coefficient();
1363 xi = mq * _num2() + _num2();
1365 xi = mp * _num2() + _num2();
1368 for (int t=0; t<6; t++) {
1369 if (xi.int_length() * maxdeg > 100000) {
1370 //std::clog << "giving up heur_gcd, xi.int_length = " << xi.int_length() << ", maxdeg = " << maxdeg << endl;
1371 throw gcdheu_failed();
1374 // Apply evaluation homomorphism and calculate GCD
1376 ex gamma = heur_gcd(p.subs(x == xi), q.subs(x == xi), &cp, &cq, var+1).expand();
1377 if (!is_ex_exactly_of_type(gamma, fail)) {
1379 // Reconstruct polynomial from GCD of mapped polynomials
1380 ex g = interpolate(gamma, xi, x);
1382 // Remove integer content
1383 g /= g.integer_content();
1385 // If the calculated polynomial divides both p and q, this is the GCD
1387 if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1389 ex lc = g.lcoeff(x);
1390 if (is_ex_exactly_of_type(lc, numeric) && ex_to_numeric(lc).is_negative())
1396 cp = interpolate(cp, xi, x);
1397 if (divide_in_z(cp, p, g, var)) {
1398 if (divide_in_z(g, q, cb ? *cb : dummy, var)) {
1402 ex lc = g.lcoeff(x);
1403 if (is_ex_exactly_of_type(lc, numeric) && ex_to_numeric(lc).is_negative())
1409 cq = interpolate(cq, xi, x);
1410 if (divide_in_z(cq, q, g, var)) {
1411 if (divide_in_z(g, p, ca ? *ca : dummy, var)) {
1415 ex lc = g.lcoeff(x);
1416 if (is_ex_exactly_of_type(lc, numeric) && ex_to_numeric(lc).is_negative())
1425 // Next evaluation point
1426 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1428 return *new ex(fail());
1432 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1435 * @param a first multivariate polynomial
1436 * @param b second multivariate polynomial
1437 * @param check_args check whether a and b are polynomials with rational
1438 * coefficients (defaults to "true")
1439 * @return the GCD as a new expression */
1440 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1442 //std::clog << "gcd(" << a << "," << b << ")\n";
1447 // GCD of numerics -> CLN
1448 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1449 numeric g = gcd(ex_to_numeric(a), ex_to_numeric(b));
1458 *ca = ex_to_numeric(a) / g;
1460 *cb = ex_to_numeric(b) / g;
1467 if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)) {
1468 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1471 // Partially factored cases (to avoid expanding large expressions)
1472 if (is_ex_exactly_of_type(a, mul)) {
1473 if (is_ex_exactly_of_type(b, mul) && b.nops() > a.nops())
1479 for (unsigned i=0; i<a.nops(); i++) {
1480 ex part_ca, part_cb;
1481 g *= gcd(a.op(i), part_b, &part_ca, &part_cb, check_args);
1490 } else if (is_ex_exactly_of_type(b, mul)) {
1491 if (is_ex_exactly_of_type(a, mul) && a.nops() > b.nops())
1497 for (unsigned i=0; i<b.nops(); i++) {
1498 ex part_ca, part_cb;
1499 g *= gcd(part_a, b.op(i), &part_ca, &part_cb, check_args);
1511 // Input polynomials of the form poly^n are sometimes also trivial
1512 if (is_ex_exactly_of_type(a, power)) {
1514 if (is_ex_exactly_of_type(b, power)) {
1515 if (p.is_equal(b.op(0))) {
1516 // a = p^n, b = p^m, gcd = p^min(n, m)
1517 ex exp_a = a.op(1), exp_b = b.op(1);
1518 if (exp_a < exp_b) {
1522 *cb = power(p, exp_b - exp_a);
1523 return power(p, exp_a);
1526 *ca = power(p, exp_a - exp_b);
1529 return power(p, exp_b);
1533 if (p.is_equal(b)) {
1534 // a = p^n, b = p, gcd = p
1536 *ca = power(p, a.op(1) - 1);
1542 } else if (is_ex_exactly_of_type(b, power)) {
1544 if (p.is_equal(a)) {
1545 // a = p, b = p^n, gcd = p
1549 *cb = power(p, b.op(1) - 1);
1555 // Some trivial cases
1556 ex aex = a.expand(), bex = b.expand();
1557 if (aex.is_zero()) {
1564 if (bex.is_zero()) {
1571 if (aex.is_equal(_ex1()) || bex.is_equal(_ex1())) {
1579 if (a.is_equal(b)) {
1588 // Gather symbol statistics
1589 sym_desc_vec sym_stats;
1590 get_symbol_stats(a, b, sym_stats);
1592 // The symbol with least degree is our main variable
1593 sym_desc_vec::const_iterator var = sym_stats.begin();
1594 const symbol &x = *(var->sym);
1596 // Cancel trivial common factor
1597 int ldeg_a = var->ldeg_a;
1598 int ldeg_b = var->ldeg_b;
1599 int min_ldeg = std::min(ldeg_a,ldeg_b);
1601 ex common = power(x, min_ldeg);
1602 //std::clog << "trivial common factor " << common << endl;
1603 return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1606 // Try to eliminate variables
1607 if (var->deg_a == 0) {
1608 //std::clog << "eliminating variable " << x << " from b" << endl;
1609 ex c = bex.content(x);
1610 ex g = gcd(aex, c, ca, cb, false);
1612 *cb *= bex.unit(x) * bex.primpart(x, c);
1614 } else if (var->deg_b == 0) {
1615 //std::clog << "eliminating variable " << x << " from a" << endl;
1616 ex c = aex.content(x);
1617 ex g = gcd(c, bex, ca, cb, false);
1619 *ca *= aex.unit(x) * aex.primpart(x, c);
1625 // Try heuristic algorithm first, fall back to PRS if that failed
1627 g = heur_gcd(aex, bex, ca, cb, var);
1628 } catch (gcdheu_failed) {
1629 g = *new ex(fail());
1631 if (is_ex_exactly_of_type(g, fail)) {
1632 //std::clog << "heuristics failed" << endl;
1637 // g = heur_gcd(aex, bex, ca, cb, var);
1638 // g = eu_gcd(aex, bex, &x);
1639 // g = euprem_gcd(aex, bex, &x);
1640 // g = peu_gcd(aex, bex, &x);
1641 // g = red_gcd(aex, bex, &x);
1642 g = sr_gcd(aex, bex, var);
1643 if (g.is_equal(_ex1())) {
1644 // Keep cofactors factored if possible
1651 divide(aex, g, *ca, false);
1653 divide(bex, g, *cb, false);
1657 if (g.is_equal(_ex1())) {
1658 // Keep cofactors factored if possible
1670 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1672 * @param a first multivariate polynomial
1673 * @param b second multivariate polynomial
1674 * @param check_args check whether a and b are polynomials with rational
1675 * coefficients (defaults to "true")
1676 * @return the LCM as a new expression */
1677 ex lcm(const ex &a, const ex &b, bool check_args)
1679 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
1680 return lcm(ex_to_numeric(a), ex_to_numeric(b));
1681 if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1682 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1685 ex g = gcd(a, b, &ca, &cb, false);
1691 * Square-free factorization
1694 // Univariate GCD of polynomials in Q[x] (used internally by sqrfree()).
1695 // a and b can be multivariate polynomials but they are treated as univariate polynomials in x.
1696 static ex univariate_gcd(const ex &a, const ex &b, const symbol &x)
1702 if (a.is_equal(_ex1()) || b.is_equal(_ex1()))
1704 if (is_ex_of_type(a, numeric) && is_ex_of_type(b, numeric))
1705 return gcd(ex_to_numeric(a), ex_to_numeric(b));
1706 if (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1707 throw(std::invalid_argument("univariate_gcd: arguments must be polynomials over the rationals"));
1709 // Euclidean algorithm
1711 if (a.degree(x) >= b.degree(x)) {
1719 r = rem(c, d, x, false);
1725 return d / d.lcoeff(x);
1729 /** Compute square-free factorization of multivariate polynomial a(x) using
1732 * @param a multivariate polynomial
1733 * @param x variable to factor in
1734 * @return factored polynomial */
1735 ex sqrfree(const ex &a, const symbol &x)
1740 ex c = univariate_gcd(a, b, x);
1742 if (c.is_equal(_ex1())) {
1746 ex y = quo(b, c, x);
1747 ex z = y - w.diff(x);
1748 while (!z.is_zero()) {
1749 ex g = univariate_gcd(w, z, x);
1757 return res * power(w, i);
1762 * Normal form of rational functions
1766 * Note: The internal normal() functions (= basic::normal() and overloaded
1767 * functions) all return lists of the form {numerator, denominator}. This
1768 * is to get around mul::eval()'s automatic expansion of numeric coefficients.
1769 * E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
1770 * the information that (a+b) is the numerator and 3 is the denominator.
1773 /** Create a symbol for replacing the expression "e" (or return a previously
1774 * assigned symbol). The symbol is appended to sym_lst and returned, the
1775 * expression is appended to repl_lst.
1776 * @see ex::normal */
1777 static ex replace_with_symbol(const ex &e, lst &sym_lst, lst &repl_lst)
1779 // Expression already in repl_lst? Then return the assigned symbol
1780 for (unsigned i=0; i<repl_lst.nops(); i++)
1781 if (repl_lst.op(i).is_equal(e))
1782 return sym_lst.op(i);
1784 // Otherwise create new symbol and add to list, taking care that the
1785 // replacement expression doesn't contain symbols from the sym_lst
1786 // because subs() is not recursive
1789 ex e_replaced = e.subs(sym_lst, repl_lst);
1791 repl_lst.append(e_replaced);
1795 /** Create a symbol for replacing the expression "e" (or return a previously
1796 * assigned symbol). An expression of the form "symbol == expression" is added
1797 * to repl_lst and the symbol is returned.
1798 * @see ex::to_rational */
1799 static ex replace_with_symbol(const ex &e, lst &repl_lst)
1801 // Expression already in repl_lst? Then return the assigned symbol
1802 for (unsigned i=0; i<repl_lst.nops(); i++)
1803 if (repl_lst.op(i).op(1).is_equal(e))
1804 return repl_lst.op(i).op(0);
1806 // Otherwise create new symbol and add to list, taking care that the
1807 // replacement expression doesn't contain symbols from the sym_lst
1808 // because subs() is not recursive
1811 ex e_replaced = e.subs(repl_lst);
1812 repl_lst.append(es == e_replaced);
1816 /** Default implementation of ex::normal(). It replaces the object with a
1818 * @see ex::normal */
1819 ex basic::normal(lst &sym_lst, lst &repl_lst, int level) const
1821 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1825 /** Implementation of ex::normal() for symbols. This returns the unmodified symbol.
1826 * @see ex::normal */
1827 ex symbol::normal(lst &sym_lst, lst &repl_lst, int level) const
1829 return (new lst(*this, _ex1()))->setflag(status_flags::dynallocated);
1833 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1834 * into re+I*im and replaces I and non-rational real numbers with a temporary
1836 * @see ex::normal */
1837 ex numeric::normal(lst &sym_lst, lst &repl_lst, int level) const
1839 numeric num = numer();
1842 if (num.is_real()) {
1843 if (!num.is_integer())
1844 numex = replace_with_symbol(numex, sym_lst, repl_lst);
1846 numeric re = num.real(), im = num.imag();
1847 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, sym_lst, repl_lst);
1848 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, sym_lst, repl_lst);
1849 numex = re_ex + im_ex * replace_with_symbol(I, sym_lst, repl_lst);
1852 // Denominator is always a real integer (see numeric::denom())
1853 return (new lst(numex, denom()))->setflag(status_flags::dynallocated);
1857 /** Fraction cancellation.
1858 * @param n numerator
1859 * @param d denominator
1860 * @return cancelled fraction {n, d} as a list */
1861 static ex frac_cancel(const ex &n, const ex &d)
1865 numeric pre_factor = _num1();
1867 //std::clog << "frac_cancel num = " << num << ", den = " << den << endl;
1869 // Handle special cases where numerator or denominator is 0
1871 return (new lst(_ex0(), _ex1()))->setflag(status_flags::dynallocated);
1872 if (den.expand().is_zero())
1873 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
1875 // Bring numerator and denominator to Z[X] by multiplying with
1876 // LCM of all coefficients' denominators
1877 numeric num_lcm = lcm_of_coefficients_denominators(num);
1878 numeric den_lcm = lcm_of_coefficients_denominators(den);
1879 num = multiply_lcm(num, num_lcm);
1880 den = multiply_lcm(den, den_lcm);
1881 pre_factor = den_lcm / num_lcm;
1883 // Cancel GCD from numerator and denominator
1885 if (gcd(num, den, &cnum, &cden, false) != _ex1()) {
1890 // Make denominator unit normal (i.e. coefficient of first symbol
1891 // as defined by get_first_symbol() is made positive)
1893 if (get_first_symbol(den, x)) {
1894 GINAC_ASSERT(is_ex_exactly_of_type(den.unit(*x),numeric));
1895 if (ex_to_numeric(den.unit(*x)).is_negative()) {
1901 // Return result as list
1902 //std::clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << endl;
1903 return (new lst(num * pre_factor.numer(), den * pre_factor.denom()))->setflag(status_flags::dynallocated);
1907 /** Implementation of ex::normal() for a sum. It expands terms and performs
1908 * fractional addition.
1909 * @see ex::normal */
1910 ex add::normal(lst &sym_lst, lst &repl_lst, int level) const
1913 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1914 else if (level == -max_recursion_level)
1915 throw(std::runtime_error("max recursion level reached"));
1917 // Normalize and expand children, chop into summands and split each
1918 // one into numerator and denominator
1919 exvector nums, dens;
1920 nums.reserve(seq.size()+1);
1921 dens.reserve(seq.size()+1);
1922 epvector::const_iterator it = seq.begin(), itend = seq.end();
1923 while (it != itend) {
1925 // Normalize and expand child
1926 ex n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1).expand();
1928 // If numerator is a sum, chop into summands
1929 if (is_ex_exactly_of_type(n.op(0), add)) {
1930 epvector::const_iterator bit = ex_to_add(n.op(0)).seq.begin(), bitend = ex_to_add(n.op(0)).seq.end();
1931 while (bit != bitend) {
1932 nums.push_back(recombine_pair_to_ex(*bit));
1933 dens.push_back(n.op(1));
1937 // The overall_coeff is already normalized (== rational), we just
1938 // split it into numerator and denominator
1939 GINAC_ASSERT(ex_to_numeric(ex_to_add(n.op(0)).overall_coeff).is_rational());
1940 numeric overall = ex_to_numeric(ex_to_add(n.op(0)).overall_coeff);
1941 nums.push_back(overall.numer());
1942 dens.push_back(overall.denom() * n.op(1));
1944 nums.push_back(n.op(0));
1945 dens.push_back(n.op(1));
1949 ex n = overall_coeff.bp->normal(sym_lst, repl_lst, level-1);
1950 nums.push_back(n.op(0));
1951 dens.push_back(n.op(1));
1952 GINAC_ASSERT(nums.size() == dens.size());
1954 // Now, nums is a vector of all numerators and dens is a vector of
1957 // Add fractions sequentially
1958 exvector::const_iterator num_it = nums.begin(), num_itend = nums.end();
1959 exvector::const_iterator den_it = dens.begin(), den_itend = dens.end();
1960 //std::clog << "add::normal uses the following summands:\n";
1961 //std::clog << " num = " << *num_it << ", den = " << *den_it << endl;
1962 ex num = *num_it++, den = *den_it++;
1963 while (num_it != num_itend) {
1964 //std::clog << " num = " << *num_it << ", den = " << *den_it << endl;
1965 ex co_den1, co_den2;
1966 ex g = gcd(den, *den_it, &co_den1, &co_den2, false);
1967 num = (num * co_den2) + (*num_it * co_den1);
1968 den *= co_den2; // this is the lcm(den, *den_it)
1971 //std::clog << " common denominator = " << den << endl;
1973 // Cancel common factors from num/den
1974 return frac_cancel(num, den);
1978 /** Implementation of ex::normal() for a product. It cancels common factors
1980 * @see ex::normal() */
1981 ex mul::normal(lst &sym_lst, lst &repl_lst, int level) const
1984 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1985 else if (level == -max_recursion_level)
1986 throw(std::runtime_error("max recursion level reached"));
1988 // Normalize children, separate into numerator and denominator
1992 epvector::const_iterator it = seq.begin(), itend = seq.end();
1993 while (it != itend) {
1994 n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1);
1999 n = overall_coeff.bp->normal(sym_lst, repl_lst, level-1);
2003 // Perform fraction cancellation
2004 return frac_cancel(num, den);
2008 /** Implementation of ex::normal() for powers. It normalizes the basis,
2009 * distributes integer exponents to numerator and denominator, and replaces
2010 * non-integer powers by temporary symbols.
2011 * @see ex::normal */
2012 ex power::normal(lst &sym_lst, lst &repl_lst, int level) const
2015 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
2016 else if (level == -max_recursion_level)
2017 throw(std::runtime_error("max recursion level reached"));
2020 ex n = basis.bp->normal(sym_lst, repl_lst, level-1);
2022 if (exponent.info(info_flags::integer)) {
2024 if (exponent.info(info_flags::positive)) {
2026 // (a/b)^n -> {a^n, b^n}
2027 return (new lst(power(n.op(0), exponent), power(n.op(1), exponent)))->setflag(status_flags::dynallocated);
2029 } else if (exponent.info(info_flags::negative)) {
2031 // (a/b)^-n -> {b^n, a^n}
2032 return (new lst(power(n.op(1), -exponent), power(n.op(0), -exponent)))->setflag(status_flags::dynallocated);
2037 if (exponent.info(info_flags::positive)) {
2039 // (a/b)^x -> {sym((a/b)^x), 1}
2040 return (new lst(replace_with_symbol(power(n.op(0) / n.op(1), exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
2042 } else if (exponent.info(info_flags::negative)) {
2044 if (n.op(1).is_equal(_ex1())) {
2046 // a^-x -> {1, sym(a^x)}
2047 return (new lst(_ex1(), replace_with_symbol(power(n.op(0), -exponent), sym_lst, repl_lst)))->setflag(status_flags::dynallocated);
2051 // (a/b)^-x -> {sym((b/a)^x), 1}
2052 return (new lst(replace_with_symbol(power(n.op(1) / n.op(0), -exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
2055 } else { // exponent not numeric
2057 // (a/b)^x -> {sym((a/b)^x, 1}
2058 return (new lst(replace_with_symbol(power(n.op(0) / n.op(1), exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
2064 /** Implementation of ex::normal() for pseries. It normalizes each coefficient and
2065 * replaces the series by a temporary symbol.
2066 * @see ex::normal */
2067 ex pseries::normal(lst &sym_lst, lst &repl_lst, int level) const
2070 new_seq.reserve(seq.size());
2072 epvector::const_iterator it = seq.begin(), itend = seq.end();
2073 while (it != itend) {
2074 new_seq.push_back(expair(it->rest.normal(), it->coeff));
2077 ex n = pseries(relational(var,point), new_seq);
2078 return (new lst(replace_with_symbol(n, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
2082 /** Implementation of ex::normal() for relationals. It normalizes both sides.
2083 * @see ex::normal */
2084 ex relational::normal(lst &sym_lst, lst &repl_lst, int level) const
2086 return (new lst(relational(lh.normal(), rh.normal(), o), _ex1()))->setflag(status_flags::dynallocated);
2090 /** Normalization of rational functions.
2091 * This function converts an expression to its normal form
2092 * "numerator/denominator", where numerator and denominator are (relatively
2093 * prime) polynomials. Any subexpressions which are not rational functions
2094 * (like non-rational numbers, non-integer powers or functions like sin(),
2095 * cos() etc.) are replaced by temporary symbols which are re-substituted by
2096 * the (normalized) subexpressions before normal() returns (this way, any
2097 * expression can be treated as a rational function). normal() is applied
2098 * recursively to arguments of functions etc.
2100 * @param level maximum depth of recursion
2101 * @return normalized expression */
2102 ex ex::normal(int level) const
2104 lst sym_lst, repl_lst;
2106 ex e = bp->normal(sym_lst, repl_lst, level);
2107 GINAC_ASSERT(is_ex_of_type(e, lst));
2109 // Re-insert replaced symbols
2110 if (sym_lst.nops() > 0)
2111 e = e.subs(sym_lst, repl_lst);
2113 // Convert {numerator, denominator} form back to fraction
2114 return e.op(0) / e.op(1);
2117 /** Numerator of an expression. If the expression is not of the normal form
2118 * "numerator/denominator", it is first converted to this form and then the
2119 * numerator is returned.
2122 * @return numerator */
2123 ex ex::numer(void) const
2125 lst sym_lst, repl_lst;
2127 ex e = bp->normal(sym_lst, repl_lst, 0);
2128 GINAC_ASSERT(is_ex_of_type(e, lst));
2130 // Re-insert replaced symbols
2131 if (sym_lst.nops() > 0)
2132 return e.op(0).subs(sym_lst, repl_lst);
2137 /** Denominator of an expression. If the expression is not of the normal form
2138 * "numerator/denominator", it is first converted to this form and then the
2139 * denominator is returned.
2142 * @return denominator */
2143 ex ex::denom(void) const
2145 lst sym_lst, repl_lst;
2147 ex e = bp->normal(sym_lst, repl_lst, 0);
2148 GINAC_ASSERT(is_ex_of_type(e, lst));
2150 // Re-insert replaced symbols
2151 if (sym_lst.nops() > 0)
2152 return e.op(1).subs(sym_lst, repl_lst);
2158 /** Default implementation of ex::to_rational(). It replaces the object with a
2160 * @see ex::to_rational */
2161 ex basic::to_rational(lst &repl_lst) const
2163 return replace_with_symbol(*this, repl_lst);
2167 /** Implementation of ex::to_rational() for symbols. This returns the
2168 * unmodified symbol.
2169 * @see ex::to_rational */
2170 ex symbol::to_rational(lst &repl_lst) const
2176 /** Implementation of ex::to_rational() for a numeric. It splits complex
2177 * numbers into re+I*im and replaces I and non-rational real numbers with a
2179 * @see ex::to_rational */
2180 ex numeric::to_rational(lst &repl_lst) const
2184 return replace_with_symbol(*this, repl_lst);
2186 numeric re = real();
2187 numeric im = imag();
2188 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl_lst);
2189 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl_lst);
2190 return re_ex + im_ex * replace_with_symbol(I, repl_lst);
2196 /** Implementation of ex::to_rational() for powers. It replaces non-integer
2197 * powers by temporary symbols.
2198 * @see ex::to_rational */
2199 ex power::to_rational(lst &repl_lst) const
2201 if (exponent.info(info_flags::integer))
2202 return power(basis.to_rational(repl_lst), exponent);
2204 return replace_with_symbol(*this, repl_lst);
2208 /** Implementation of ex::to_rational() for expairseqs.
2209 * @see ex::to_rational */
2210 ex expairseq::to_rational(lst &repl_lst) const
2213 s.reserve(seq.size());
2214 for (epvector::const_iterator it=seq.begin(); it!=seq.end(); ++it) {
2215 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*it).to_rational(repl_lst)));
2216 // s.push_back(combine_ex_with_coeff_to_pair((*it).rest.to_rational(repl_lst),
2218 ex oc = overall_coeff.to_rational(repl_lst);
2219 if (oc.info(info_flags::numeric))
2220 return thisexpairseq(s, overall_coeff);
2221 else s.push_back(combine_ex_with_coeff_to_pair(oc,_ex1()));
2222 return thisexpairseq(s, default_overall_coeff());
2226 /** Rationalization of non-rational functions.
2227 * This function converts a general expression to a rational polynomial
2228 * by replacing all non-rational subexpressions (like non-rational numbers,
2229 * non-integer powers or functions like sin(), cos() etc.) to temporary
2230 * symbols. This makes it possible to use functions like gcd() and divide()
2231 * on non-rational functions by applying to_rational() on the arguments,
2232 * calling the desired function and re-substituting the temporary symbols
2233 * in the result. To make the last step possible, all temporary symbols and
2234 * their associated expressions are collected in the list specified by the
2235 * repl_lst parameter in the form {symbol == expression}, ready to be passed
2236 * as an argument to ex::subs().
2238 * @param repl_lst collects a list of all temporary symbols and their replacements
2239 * @return rationalized expression */
2240 ex ex::to_rational(lst &repl_lst) const
2242 return bp->to_rational(repl_lst);
2246 #ifndef NO_NAMESPACE_GINAC
2247 } // namespace GiNaC
2248 #endif // ndef NO_NAMESPACE_GINAC