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
34 #include "expairseq.h"
41 #include "relational.h"
48 // If comparing expressions (ex::compare()) is fast, you can set this to 1.
49 // Some routines like quo(), rem() and gcd() will then return a quick answer
50 // when they are called with two identical arguments.
51 #define FAST_COMPARE 1
53 // Set this if you want divide_in_z() to use remembering
54 #define USE_REMEMBER 0
56 // Set this if you want divide_in_z() to use trial division followed by
57 // polynomial interpolation (always slower except for completely dense
59 #define USE_TRIAL_DIVISION 0
61 // Set this to enable some statistical output for the GCD routines
66 // Statistics variables
67 static int gcd_called = 0;
68 static int sr_gcd_called = 0;
69 static int heur_gcd_called = 0;
70 static int heur_gcd_failed = 0;
72 // Print statistics at end of program
73 static struct _stat_print {
76 cout << "gcd() called " << gcd_called << " times\n";
77 cout << "sr_gcd() called " << sr_gcd_called << " times\n";
78 cout << "heur_gcd() called " << heur_gcd_called << " times\n";
79 cout << "heur_gcd() failed " << heur_gcd_failed << " times\n";
85 /** Return pointer to first symbol found in expression. Due to GiNaCĀ“s
86 * internal ordering of terms, it may not be obvious which symbol this
87 * function returns for a given expression.
89 * @param e expression to search
90 * @param x pointer to first symbol found (returned)
91 * @return "false" if no symbol was found, "true" otherwise */
92 static bool get_first_symbol(const ex &e, const symbol *&x)
94 if (is_ex_exactly_of_type(e, symbol)) {
95 x = static_cast<symbol *>(e.bp);
97 } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
98 for (unsigned i=0; i<e.nops(); i++)
99 if (get_first_symbol(e.op(i), x))
101 } else if (is_ex_exactly_of_type(e, power)) {
102 if (get_first_symbol(e.op(0), x))
110 * Statistical information about symbols in polynomials
113 /** This structure holds information about the highest and lowest degrees
114 * in which a symbol appears in two multivariate polynomials "a" and "b".
115 * A vector of these structures with information about all symbols in
116 * two polynomials can be created with the function get_symbol_stats().
118 * @see get_symbol_stats */
120 /** Pointer to symbol */
123 /** Highest degree of symbol in polynomial "a" */
126 /** Highest degree of symbol in polynomial "b" */
129 /** Lowest degree of symbol in polynomial "a" */
132 /** Lowest degree of symbol in polynomial "b" */
135 /** Maximum of deg_a and deg_b (Used for sorting) */
138 /** Maximum number of terms of leading coefficient of symbol in both polynomials */
141 /** Commparison operator for sorting */
142 bool operator<(const sym_desc &x) const
144 if (max_deg == x.max_deg)
145 return max_lcnops < x.max_lcnops;
147 return max_deg < x.max_deg;
151 // Vector of sym_desc structures
152 typedef std::vector<sym_desc> sym_desc_vec;
154 // Add symbol the sym_desc_vec (used internally by get_symbol_stats())
155 static void add_symbol(const symbol *s, sym_desc_vec &v)
157 sym_desc_vec::iterator it = v.begin(), itend = v.end();
158 while (it != itend) {
159 if (it->sym->compare(*s) == 0) // If it's already in there, don't add it a second time
168 // Collect all symbols of an expression (used internally by get_symbol_stats())
169 static void collect_symbols(const ex &e, sym_desc_vec &v)
171 if (is_ex_exactly_of_type(e, symbol)) {
172 add_symbol(static_cast<symbol *>(e.bp), v);
173 } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
174 for (unsigned i=0; i<e.nops(); i++)
175 collect_symbols(e.op(i), v);
176 } else if (is_ex_exactly_of_type(e, power)) {
177 collect_symbols(e.op(0), v);
181 /** Collect statistical information about symbols in polynomials.
182 * This function fills in a vector of "sym_desc" structs which contain
183 * information about the highest and lowest degrees of all symbols that
184 * appear in two polynomials. The vector is then sorted by minimum
185 * degree (lowest to highest). The information gathered by this
186 * function is used by the GCD routines to identify trivial factors
187 * and to determine which variable to choose as the main variable
188 * for GCD computation.
190 * @param a first multivariate polynomial
191 * @param b second multivariate polynomial
192 * @param v vector of sym_desc structs (filled in) */
193 static void get_symbol_stats(const ex &a, const ex &b, sym_desc_vec &v)
195 collect_symbols(a.eval(), v); // eval() to expand assigned symbols
196 collect_symbols(b.eval(), v);
197 sym_desc_vec::iterator it = v.begin(), itend = v.end();
198 while (it != itend) {
199 int deg_a = a.degree(*(it->sym));
200 int deg_b = b.degree(*(it->sym));
203 it->max_deg = std::max(deg_a, deg_b);
204 it->max_lcnops = std::max(a.lcoeff(*(it->sym)).nops(), b.lcoeff(*(it->sym)).nops());
205 it->ldeg_a = a.ldegree(*(it->sym));
206 it->ldeg_b = b.ldegree(*(it->sym));
209 sort(v.begin(), v.end());
211 std::clog << "Symbols:\n";
212 it = v.begin(); itend = v.end();
213 while (it != itend) {
214 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 << ", max_lcnops=" << it->max_lcnops << endl;
215 std::clog << " lcoeff_a=" << a.lcoeff(*(it->sym)) << ", lcoeff_b=" << b.lcoeff(*(it->sym)) << endl;
223 * Computation of LCM of denominators of coefficients of a polynomial
226 // Compute LCM of denominators of coefficients by going through the
227 // expression recursively (used internally by lcm_of_coefficients_denominators())
228 static numeric lcmcoeff(const ex &e, const numeric &l)
230 if (e.info(info_flags::rational))
231 return lcm(ex_to<numeric>(e).denom(), l);
232 else if (is_ex_exactly_of_type(e, add)) {
234 for (unsigned i=0; i<e.nops(); i++)
235 c = lcmcoeff(e.op(i), c);
237 } else if (is_ex_exactly_of_type(e, mul)) {
239 for (unsigned i=0; i<e.nops(); i++)
240 c *= lcmcoeff(e.op(i), _num1());
242 } else if (is_ex_exactly_of_type(e, power)) {
243 if (is_ex_exactly_of_type(e.op(0), symbol))
246 return pow(lcmcoeff(e.op(0), l), ex_to<numeric>(e.op(1)));
251 /** Compute LCM of denominators of coefficients of a polynomial.
252 * Given a polynomial with rational coefficients, this function computes
253 * the LCM of the denominators of all coefficients. This can be used
254 * to bring a polynomial from Q[X] to Z[X].
256 * @param e multivariate polynomial (need not be expanded)
257 * @return LCM of denominators of coefficients */
258 static numeric lcm_of_coefficients_denominators(const ex &e)
260 return lcmcoeff(e, _num1());
263 /** Bring polynomial from Q[X] to Z[X] by multiplying in the previously
264 * determined LCM of the coefficient's denominators.
266 * @param e multivariate polynomial (need not be expanded)
267 * @param lcm LCM to multiply in */
268 static ex multiply_lcm(const ex &e, const numeric &lcm)
270 if (is_ex_exactly_of_type(e, mul)) {
272 numeric lcm_accum = _num1();
273 for (unsigned i=0; i<e.nops(); i++) {
274 numeric op_lcm = lcmcoeff(e.op(i), _num1());
275 c *= multiply_lcm(e.op(i), op_lcm);
278 c *= lcm / lcm_accum;
280 } else if (is_ex_exactly_of_type(e, add)) {
282 for (unsigned i=0; i<e.nops(); i++)
283 c += multiply_lcm(e.op(i), lcm);
285 } else if (is_ex_exactly_of_type(e, power)) {
286 if (is_ex_exactly_of_type(e.op(0), symbol))
289 return pow(multiply_lcm(e.op(0), lcm.power(ex_to<numeric>(e.op(1)).inverse())), e.op(1));
295 /** Compute the integer content (= GCD of all numeric coefficients) of an
296 * expanded polynomial.
298 * @param e expanded polynomial
299 * @return integer content */
300 numeric ex::integer_content(void) const
303 return bp->integer_content();
306 numeric basic::integer_content(void) const
311 numeric numeric::integer_content(void) const
316 numeric add::integer_content(void) const
318 epvector::const_iterator it = seq.begin();
319 epvector::const_iterator itend = seq.end();
321 while (it != itend) {
322 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
323 GINAC_ASSERT(is_ex_exactly_of_type(it->coeff,numeric));
324 c = gcd(ex_to<numeric>(it->coeff), c);
327 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
328 c = gcd(ex_to<numeric>(overall_coeff),c);
332 numeric mul::integer_content(void) const
334 #ifdef DO_GINAC_ASSERT
335 epvector::const_iterator it = seq.begin();
336 epvector::const_iterator itend = seq.end();
337 while (it != itend) {
338 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
341 #endif // def DO_GINAC_ASSERT
342 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
343 return abs(ex_to<numeric>(overall_coeff));
348 * Polynomial quotients and remainders
351 /** Quotient q(x) of polynomials a(x) and b(x) in Q[x].
352 * It satisfies a(x)=b(x)*q(x)+r(x).
354 * @param a first polynomial in x (dividend)
355 * @param b second polynomial in x (divisor)
356 * @param x a and b are polynomials in x
357 * @param check_args check whether a and b are polynomials with rational
358 * coefficients (defaults to "true")
359 * @return quotient of a and b in Q[x] */
360 ex quo(const ex &a, const ex &b, const symbol &x, bool check_args)
363 throw(std::overflow_error("quo: division by zero"));
364 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
370 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
371 throw(std::invalid_argument("quo: arguments must be polynomials over the rationals"));
373 // Polynomial long division
378 int bdeg = b.degree(x);
379 int rdeg = r.degree(x);
380 ex blcoeff = b.expand().coeff(x, bdeg);
381 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
382 while (rdeg >= bdeg) {
383 ex term, rcoeff = r.coeff(x, rdeg);
384 if (blcoeff_is_numeric)
385 term = rcoeff / blcoeff;
387 if (!divide(rcoeff, blcoeff, term, false))
388 return (new fail())->setflag(status_flags::dynallocated);
390 term *= power(x, rdeg - bdeg);
392 r -= (term * b).expand();
401 /** Remainder r(x) of polynomials a(x) and b(x) in Q[x].
402 * It satisfies a(x)=b(x)*q(x)+r(x).
404 * @param a first polynomial in x (dividend)
405 * @param b second polynomial in x (divisor)
406 * @param x a and b are polynomials in x
407 * @param check_args check whether a and b are polynomials with rational
408 * coefficients (defaults to "true")
409 * @return remainder of a(x) and b(x) in Q[x] */
410 ex rem(const ex &a, const ex &b, const symbol &x, bool check_args)
413 throw(std::overflow_error("rem: division by zero"));
414 if (is_ex_exactly_of_type(a, numeric)) {
415 if (is_ex_exactly_of_type(b, numeric))
424 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
425 throw(std::invalid_argument("rem: arguments must be polynomials over the rationals"));
427 // Polynomial long division
431 int bdeg = b.degree(x);
432 int rdeg = r.degree(x);
433 ex blcoeff = b.expand().coeff(x, bdeg);
434 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
435 while (rdeg >= bdeg) {
436 ex term, rcoeff = r.coeff(x, rdeg);
437 if (blcoeff_is_numeric)
438 term = rcoeff / blcoeff;
440 if (!divide(rcoeff, blcoeff, term, false))
441 return (new fail())->setflag(status_flags::dynallocated);
443 term *= power(x, rdeg - bdeg);
444 r -= (term * b).expand();
453 /** Pseudo-remainder of polynomials a(x) and b(x) in Z[x].
455 * @param a first polynomial in x (dividend)
456 * @param b second polynomial in x (divisor)
457 * @param x a and b are polynomials in x
458 * @param check_args check whether a and b are polynomials with rational
459 * coefficients (defaults to "true")
460 * @return pseudo-remainder of a(x) and b(x) in Z[x] */
461 ex prem(const ex &a, const ex &b, const symbol &x, bool check_args)
464 throw(std::overflow_error("prem: division by zero"));
465 if (is_ex_exactly_of_type(a, numeric)) {
466 if (is_ex_exactly_of_type(b, numeric))
471 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
472 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
474 // Polynomial long division
477 int rdeg = r.degree(x);
478 int bdeg = eb.degree(x);
481 blcoeff = eb.coeff(x, bdeg);
485 eb -= blcoeff * power(x, bdeg);
489 int delta = rdeg - bdeg + 1, i = 0;
490 while (rdeg >= bdeg && !r.is_zero()) {
491 ex rlcoeff = r.coeff(x, rdeg);
492 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
496 r -= rlcoeff * power(x, rdeg);
497 r = (blcoeff * r).expand() - term;
501 return power(blcoeff, delta - i) * r;
505 /** Sparse pseudo-remainder of polynomials a(x) and b(x) in Z[x].
507 * @param a first polynomial in x (dividend)
508 * @param b second polynomial in x (divisor)
509 * @param x a and b are polynomials in x
510 * @param check_args check whether a and b are polynomials with rational
511 * coefficients (defaults to "true")
512 * @return sparse pseudo-remainder of a(x) and b(x) in Z[x] */
514 ex sprem(const ex &a, const ex &b, const symbol &x, bool check_args)
517 throw(std::overflow_error("prem: division by zero"));
518 if (is_ex_exactly_of_type(a, numeric)) {
519 if (is_ex_exactly_of_type(b, numeric))
524 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
525 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
527 // Polynomial long division
530 int rdeg = r.degree(x);
531 int bdeg = eb.degree(x);
534 blcoeff = eb.coeff(x, bdeg);
538 eb -= blcoeff * power(x, bdeg);
542 while (rdeg >= bdeg && !r.is_zero()) {
543 ex rlcoeff = r.coeff(x, rdeg);
544 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
548 r -= rlcoeff * power(x, rdeg);
549 r = (blcoeff * r).expand() - term;
556 /** Exact polynomial division of a(X) by b(X) in Q[X].
558 * @param a first multivariate polynomial (dividend)
559 * @param b second multivariate polynomial (divisor)
560 * @param q quotient (returned)
561 * @param check_args check whether a and b are polynomials with rational
562 * coefficients (defaults to "true")
563 * @return "true" when exact division succeeds (quotient returned in q),
564 * "false" otherwise */
565 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
569 throw(std::overflow_error("divide: division by zero"));
572 if (is_ex_exactly_of_type(b, numeric)) {
575 } else if (is_ex_exactly_of_type(a, numeric))
583 if (check_args && (!a.info(info_flags::rational_polynomial) ||
584 !b.info(info_flags::rational_polynomial)))
585 throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
589 if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
590 throw(std::invalid_argument("invalid expression in divide()"));
592 // Polynomial long division (recursive)
596 int bdeg = b.degree(*x);
597 int rdeg = r.degree(*x);
598 ex blcoeff = b.expand().coeff(*x, bdeg);
599 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
600 while (rdeg >= bdeg) {
601 ex term, rcoeff = r.coeff(*x, rdeg);
602 if (blcoeff_is_numeric)
603 term = rcoeff / blcoeff;
605 if (!divide(rcoeff, blcoeff, term, false))
607 term *= power(*x, rdeg - bdeg);
609 r -= (term * b).expand();
623 typedef std::pair<ex, ex> ex2;
624 typedef std::pair<ex, bool> exbool;
627 bool operator() (const ex2 &p, const ex2 &q) const
629 int cmp = p.first.compare(q.first);
630 return ((cmp<0) || (!(cmp>0) && p.second.compare(q.second)<0));
634 typedef std::map<ex2, exbool, ex2_less> ex2_exbool_remember;
638 /** Exact polynomial division of a(X) by b(X) in Z[X].
639 * This functions works like divide() but the input and output polynomials are
640 * in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
641 * divide(), it doesnĀ“t check whether the input polynomials really are integer
642 * polynomials, so be careful of what you pass in. Also, you have to run
643 * get_symbol_stats() over the input polynomials before calling this function
644 * and pass an iterator to the first element of the sym_desc vector. This
645 * function is used internally by the heur_gcd().
647 * @param a first multivariate polynomial (dividend)
648 * @param b second multivariate polynomial (divisor)
649 * @param q quotient (returned)
650 * @param var iterator to first element of vector of sym_desc structs
651 * @return "true" when exact division succeeds (the quotient is returned in
652 * q), "false" otherwise.
653 * @see get_symbol_stats, heur_gcd */
654 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
658 throw(std::overflow_error("divide_in_z: division by zero"));
659 if (b.is_equal(_ex1())) {
663 if (is_ex_exactly_of_type(a, numeric)) {
664 if (is_ex_exactly_of_type(b, numeric)) {
666 return q.info(info_flags::integer);
679 static ex2_exbool_remember dr_remember;
680 ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
681 if (remembered != dr_remember.end()) {
682 q = remembered->second.first;
683 return remembered->second.second;
688 const symbol *x = var->sym;
691 int adeg = a.degree(*x), bdeg = b.degree(*x);
695 #if USE_TRIAL_DIVISION
697 // Trial division with polynomial interpolation
700 // Compute values at evaluation points 0..adeg
701 vector<numeric> alpha; alpha.reserve(adeg + 1);
702 exvector u; u.reserve(adeg + 1);
703 numeric point = _num0();
705 for (i=0; i<=adeg; i++) {
706 ex bs = b.subs(*x == point);
707 while (bs.is_zero()) {
709 bs = b.subs(*x == point);
711 if (!divide_in_z(a.subs(*x == point), bs, c, var+1))
713 alpha.push_back(point);
719 vector<numeric> rcp; rcp.reserve(adeg + 1);
720 rcp.push_back(_num0());
721 for (k=1; k<=adeg; k++) {
722 numeric product = alpha[k] - alpha[0];
724 product *= alpha[k] - alpha[i];
725 rcp.push_back(product.inverse());
728 // Compute Newton coefficients
729 exvector v; v.reserve(adeg + 1);
731 for (k=1; k<=adeg; k++) {
733 for (i=k-2; i>=0; i--)
734 temp = temp * (alpha[k] - alpha[i]) + v[i];
735 v.push_back((u[k] - temp) * rcp[k]);
738 // Convert from Newton form to standard form
740 for (k=adeg-1; k>=0; k--)
741 c = c * (*x - alpha[k]) + v[k];
743 if (c.degree(*x) == (adeg - bdeg)) {
751 // Polynomial long division (recursive)
757 ex blcoeff = eb.coeff(*x, bdeg);
758 while (rdeg >= bdeg) {
759 ex term, rcoeff = r.coeff(*x, rdeg);
760 if (!divide_in_z(rcoeff, blcoeff, term, var+1))
762 term = (term * power(*x, rdeg - bdeg)).expand();
764 r -= (term * eb).expand();
767 dr_remember[ex2(a, b)] = exbool(q, true);
774 dr_remember[ex2(a, b)] = exbool(q, false);
783 * Separation of unit part, content part and primitive part of polynomials
786 /** Compute unit part (= sign of leading coefficient) of a multivariate
787 * polynomial in Z[x]. The product of unit part, content part, and primitive
788 * part is the polynomial itself.
790 * @param x variable in which to compute the unit part
792 * @see ex::content, ex::primpart */
793 ex ex::unit(const symbol &x) const
795 ex c = expand().lcoeff(x);
796 if (is_ex_exactly_of_type(c, numeric))
797 return c < _ex0() ? _ex_1() : _ex1();
800 if (get_first_symbol(c, y))
803 throw(std::invalid_argument("invalid expression in unit()"));
808 /** Compute content part (= unit normal GCD of all coefficients) of a
809 * multivariate polynomial in Z[x]. The product of unit part, content part,
810 * and primitive part is the polynomial itself.
812 * @param x variable in which to compute the content part
813 * @return content part
814 * @see ex::unit, ex::primpart */
815 ex ex::content(const symbol &x) const
819 if (is_ex_exactly_of_type(*this, numeric))
820 return info(info_flags::negative) ? -*this : *this;
825 // First, try the integer content
826 ex c = e.integer_content();
828 ex lcoeff = r.lcoeff(x);
829 if (lcoeff.info(info_flags::integer))
832 // GCD of all coefficients
833 int deg = e.degree(x);
834 int ldeg = e.ldegree(x);
836 return e.lcoeff(x) / e.unit(x);
838 for (int i=ldeg; i<=deg; i++)
839 c = gcd(e.coeff(x, i), c, NULL, NULL, false);
844 /** Compute primitive part of a multivariate polynomial in Z[x].
845 * The product of unit part, content part, and primitive part is the
848 * @param x variable in which to compute the primitive part
849 * @return primitive part
850 * @see ex::unit, ex::content */
851 ex ex::primpart(const symbol &x) const
855 if (is_ex_exactly_of_type(*this, numeric))
862 if (is_ex_exactly_of_type(c, numeric))
863 return *this / (c * u);
865 return quo(*this, c * u, x, false);
869 /** Compute primitive part of a multivariate polynomial in Z[x] when the
870 * content part is already known. This function is faster in computing the
871 * primitive part than the previous function.
873 * @param x variable in which to compute the primitive part
874 * @param c previously computed content part
875 * @return primitive part */
876 ex ex::primpart(const symbol &x, const ex &c) const
882 if (is_ex_exactly_of_type(*this, numeric))
886 if (is_ex_exactly_of_type(c, numeric))
887 return *this / (c * u);
889 return quo(*this, c * u, x, false);
894 * GCD of multivariate polynomials
897 /** Compute GCD of polynomials in Q[X] using the Euclidean algorithm (not
898 * really suited for multivariate GCDs). This function is only provided for
901 * @param a first multivariate polynomial
902 * @param b second multivariate polynomial
903 * @param x pointer to symbol (main variable) in which to compute the GCD in
904 * @return the GCD as a new expression
907 static ex eu_gcd(const ex &a, const ex &b, const symbol *x)
909 //std::clog << "eu_gcd(" << a << "," << b << ")\n";
911 // Sort c and d so that c has higher degree
913 int adeg = a.degree(*x), bdeg = b.degree(*x);
923 c = c / c.lcoeff(*x);
924 d = d / d.lcoeff(*x);
926 // Euclidean algorithm
929 //std::clog << " d = " << d << endl;
930 r = rem(c, d, *x, false);
932 return d / d.lcoeff(*x);
939 /** Compute GCD of multivariate polynomials using the Euclidean PRS algorithm
940 * with pseudo-remainders ("World's Worst GCD Algorithm", staying in Z[X]).
941 * This function is only provided for testing purposes.
943 * @param a first multivariate polynomial
944 * @param b second multivariate polynomial
945 * @param x pointer to symbol (main variable) in which to compute the GCD in
946 * @return the GCD as a new expression
949 static ex euprem_gcd(const ex &a, const ex &b, const symbol *x)
951 //std::clog << "euprem_gcd(" << a << "," << b << ")\n";
953 // Sort c and d so that c has higher degree
955 int adeg = a.degree(*x), bdeg = b.degree(*x);
964 // Calculate GCD of contents
965 ex gamma = gcd(c.content(*x), d.content(*x), NULL, NULL, false);
967 // Euclidean algorithm with pseudo-remainders
970 //std::clog << " d = " << d << endl;
971 r = prem(c, d, *x, false);
973 return d.primpart(*x) * gamma;
980 /** Compute GCD of multivariate polynomials using the primitive Euclidean
981 * PRS algorithm (complete content removal at each step). This function is
982 * only provided for testing purposes.
984 * @param a first multivariate polynomial
985 * @param b second multivariate polynomial
986 * @param x pointer to symbol (main variable) in which to compute the GCD in
987 * @return the GCD as a new expression
990 static ex peu_gcd(const ex &a, const ex &b, const symbol *x)
992 //std::clog << "peu_gcd(" << a << "," << b << ")\n";
994 // Sort c and d so that c has higher degree
996 int adeg = a.degree(*x), bdeg = b.degree(*x);
1008 // Remove content from c and d, to be attached to GCD later
1009 ex cont_c = c.content(*x);
1010 ex cont_d = d.content(*x);
1011 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1014 c = c.primpart(*x, cont_c);
1015 d = d.primpart(*x, cont_d);
1017 // Euclidean algorithm with content removal
1020 //std::clog << " d = " << d << endl;
1021 r = prem(c, d, *x, false);
1030 /** Compute GCD of multivariate polynomials using the reduced PRS algorithm.
1031 * This function is only provided for testing purposes.
1033 * @param a first multivariate polynomial
1034 * @param b second multivariate polynomial
1035 * @param x pointer to symbol (main variable) in which to compute the GCD in
1036 * @return the GCD as a new expression
1039 static ex red_gcd(const ex &a, const ex &b, const symbol *x)
1041 //std::clog << "red_gcd(" << a << "," << b << ")\n";
1043 // Sort c and d so that c has higher degree
1045 int adeg = a.degree(*x), bdeg = b.degree(*x);
1059 // Remove content from c and d, to be attached to GCD later
1060 ex cont_c = c.content(*x);
1061 ex cont_d = d.content(*x);
1062 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1065 c = c.primpart(*x, cont_c);
1066 d = d.primpart(*x, cont_d);
1068 // First element of divisor sequence
1070 int delta = cdeg - ddeg;
1073 // Calculate polynomial pseudo-remainder
1074 //std::clog << " d = " << d << endl;
1075 r = prem(c, d, *x, false);
1077 return gamma * d.primpart(*x);
1081 if (!divide(r, pow(ri, delta), d, false))
1082 throw(std::runtime_error("invalid expression in red_gcd(), division failed"));
1083 ddeg = d.degree(*x);
1085 if (is_ex_exactly_of_type(r, numeric))
1088 return gamma * r.primpart(*x);
1091 ri = c.expand().lcoeff(*x);
1092 delta = cdeg - ddeg;
1097 /** Compute GCD of multivariate polynomials using the subresultant PRS
1098 * algorithm. This function is used internally by gcd().
1100 * @param a first multivariate polynomial
1101 * @param b second multivariate polynomial
1102 * @param var iterator to first element of vector of sym_desc structs
1103 * @return the GCD as a new expression
1106 static ex sr_gcd(const ex &a, const ex &b, sym_desc_vec::const_iterator var)
1108 //std::clog << "sr_gcd(" << a << "," << b << ")\n";
1113 // The first symbol is our main variable
1114 const symbol &x = *(var->sym);
1116 // Sort c and d so that c has higher degree
1118 int adeg = a.degree(x), bdeg = b.degree(x);
1132 // Remove content from c and d, to be attached to GCD later
1133 ex cont_c = c.content(x);
1134 ex cont_d = d.content(x);
1135 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1138 c = c.primpart(x, cont_c);
1139 d = d.primpart(x, cont_d);
1140 //std::clog << " content " << gamma << " removed, continuing with sr_gcd(" << c << "," << d << ")\n";
1142 // First element of subresultant sequence
1143 ex r = _ex0(), ri = _ex1(), psi = _ex1();
1144 int delta = cdeg - ddeg;
1147 // Calculate polynomial pseudo-remainder
1148 //std::clog << " start of loop, psi = " << psi << ", calculating pseudo-remainder...\n";
1149 //std::clog << " d = " << d << endl;
1150 r = prem(c, d, x, false);
1152 return gamma * d.primpart(x);
1155 //std::clog << " dividing...\n";
1156 if (!divide_in_z(r, ri * pow(psi, delta), d, var))
1157 throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
1160 if (is_ex_exactly_of_type(r, numeric))
1163 return gamma * r.primpart(x);
1166 // Next element of subresultant sequence
1167 //std::clog << " calculating next subresultant...\n";
1168 ri = c.expand().lcoeff(x);
1172 divide_in_z(pow(ri, delta), pow(psi, delta-1), psi, var+1);
1173 delta = cdeg - ddeg;
1178 /** Return maximum (absolute value) coefficient of a polynomial.
1179 * This function is used internally by heur_gcd().
1181 * @param e expanded multivariate polynomial
1182 * @return maximum coefficient
1184 numeric ex::max_coefficient(void) const
1186 GINAC_ASSERT(bp!=0);
1187 return bp->max_coefficient();
1190 /** Implementation ex::max_coefficient().
1192 numeric basic::max_coefficient(void) const
1197 numeric numeric::max_coefficient(void) const
1202 numeric add::max_coefficient(void) const
1204 epvector::const_iterator it = seq.begin();
1205 epvector::const_iterator itend = seq.end();
1206 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1207 numeric cur_max = abs(ex_to<numeric>(overall_coeff));
1208 while (it != itend) {
1210 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
1211 a = abs(ex_to<numeric>(it->coeff));
1219 numeric mul::max_coefficient(void) const
1221 #ifdef DO_GINAC_ASSERT
1222 epvector::const_iterator it = seq.begin();
1223 epvector::const_iterator itend = seq.end();
1224 while (it != itend) {
1225 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
1228 #endif // def DO_GINAC_ASSERT
1229 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1230 return abs(ex_to<numeric>(overall_coeff));
1234 /** Apply symmetric modular homomorphism to a multivariate polynomial.
1235 * This function is used internally by heur_gcd().
1237 * @param e expanded multivariate polynomial
1239 * @return mapped polynomial
1241 ex ex::smod(const numeric &xi) const
1243 GINAC_ASSERT(bp!=0);
1244 return bp->smod(xi);
1247 ex basic::smod(const numeric &xi) const
1252 ex numeric::smod(const numeric &xi) const
1254 return GiNaC::smod(*this, xi);
1257 ex add::smod(const numeric &xi) const
1260 newseq.reserve(seq.size()+1);
1261 epvector::const_iterator it = seq.begin();
1262 epvector::const_iterator itend = seq.end();
1263 while (it != itend) {
1264 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
1265 numeric coeff = GiNaC::smod(ex_to<numeric>(it->coeff), xi);
1266 if (!coeff.is_zero())
1267 newseq.push_back(expair(it->rest, coeff));
1270 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1271 numeric coeff = GiNaC::smod(ex_to<numeric>(overall_coeff), xi);
1272 return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
1275 ex mul::smod(const numeric &xi) const
1277 #ifdef DO_GINAC_ASSERT
1278 epvector::const_iterator it = seq.begin();
1279 epvector::const_iterator itend = seq.end();
1280 while (it != itend) {
1281 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
1284 #endif // def DO_GINAC_ASSERT
1285 mul * mulcopyp = new mul(*this);
1286 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1287 mulcopyp->overall_coeff = GiNaC::smod(ex_to<numeric>(overall_coeff),xi);
1288 mulcopyp->clearflag(status_flags::evaluated);
1289 mulcopyp->clearflag(status_flags::hash_calculated);
1290 return mulcopyp->setflag(status_flags::dynallocated);
1294 /** xi-adic polynomial interpolation */
1295 static ex interpolate(const ex &gamma, const numeric &xi, const symbol &x)
1299 numeric rxi = xi.inverse();
1300 for (int i=0; !e.is_zero(); i++) {
1302 g += gi * power(x, i);
1308 /** Exception thrown by heur_gcd() to signal failure. */
1309 class gcdheu_failed {};
1311 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1312 * get_symbol_stats() must have been called previously with the input
1313 * polynomials and an iterator to the first element of the sym_desc vector
1314 * passed in. This function is used internally by gcd().
1316 * @param a first multivariate polynomial (expanded)
1317 * @param b second multivariate polynomial (expanded)
1318 * @param ca cofactor of polynomial a (returned), NULL to suppress
1319 * calculation of cofactor
1320 * @param cb cofactor of polynomial b (returned), NULL to suppress
1321 * calculation of cofactor
1322 * @param var iterator to first element of vector of sym_desc structs
1323 * @return the GCD as a new expression
1325 * @exception gcdheu_failed() */
1326 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
1328 //std::clog << "heur_gcd(" << a << "," << b << ")\n";
1333 // Algorithms only works for non-vanishing input polynomials
1334 if (a.is_zero() || b.is_zero())
1335 return (new fail())->setflag(status_flags::dynallocated);
1337 // GCD of two numeric values -> CLN
1338 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1339 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1341 *ca = ex_to<numeric>(a) / g;
1343 *cb = ex_to<numeric>(b) / g;
1347 // The first symbol is our main variable
1348 const symbol &x = *(var->sym);
1350 // Remove integer content
1351 numeric gc = gcd(a.integer_content(), b.integer_content());
1352 numeric rgc = gc.inverse();
1355 int maxdeg = std::max(p.degree(x),q.degree(x));
1357 // Find evaluation point
1358 numeric mp = p.max_coefficient();
1359 numeric mq = q.max_coefficient();
1362 xi = mq * _num2() + _num2();
1364 xi = mp * _num2() + _num2();
1367 for (int t=0; t<6; t++) {
1368 if (xi.int_length() * maxdeg > 100000) {
1369 //std::clog << "giving up heur_gcd, xi.int_length = " << xi.int_length() << ", maxdeg = " << maxdeg << std::endl;
1370 throw gcdheu_failed();
1373 // Apply evaluation homomorphism and calculate GCD
1375 ex gamma = heur_gcd(p.subs(x == xi), q.subs(x == xi), &cp, &cq, var+1).expand();
1376 if (!is_ex_exactly_of_type(gamma, fail)) {
1378 // Reconstruct polynomial from GCD of mapped polynomials
1379 ex g = interpolate(gamma, xi, x);
1381 // Remove integer content
1382 g /= g.integer_content();
1384 // If the calculated polynomial divides both p and q, this is the GCD
1386 if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1388 ex lc = g.lcoeff(x);
1389 if (is_ex_exactly_of_type(lc, numeric) && ex_to<numeric>(lc).is_negative())
1395 cp = interpolate(cp, xi, x);
1396 if (divide_in_z(cp, p, g, var)) {
1397 if (divide_in_z(g, q, cb ? *cb : dummy, var)) {
1401 ex lc = g.lcoeff(x);
1402 if (is_ex_exactly_of_type(lc, numeric) && ex_to<numeric>(lc).is_negative())
1408 cq = interpolate(cq, xi, x);
1409 if (divide_in_z(cq, q, g, var)) {
1410 if (divide_in_z(g, p, ca ? *ca : dummy, var)) {
1414 ex lc = g.lcoeff(x);
1415 if (is_ex_exactly_of_type(lc, numeric) && ex_to<numeric>(lc).is_negative())
1424 // Next evaluation point
1425 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1427 return (new fail())->setflag(status_flags::dynallocated);
1431 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1434 * @param a first multivariate polynomial
1435 * @param b second multivariate polynomial
1436 * @param check_args check whether a and b are polynomials with rational
1437 * coefficients (defaults to "true")
1438 * @return the GCD as a new expression */
1439 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1441 //std::clog << "gcd(" << a << "," << b << ")\n";
1446 // GCD of numerics -> CLN
1447 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1448 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1457 *ca = ex_to<numeric>(a) / g;
1459 *cb = ex_to<numeric>(b) / g;
1466 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))) {
1467 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1470 // Partially factored cases (to avoid expanding large expressions)
1471 if (is_ex_exactly_of_type(a, mul)) {
1472 if (is_ex_exactly_of_type(b, mul) && b.nops() > a.nops())
1478 for (unsigned i=0; i<a.nops(); i++) {
1479 ex part_ca, part_cb;
1480 g *= gcd(a.op(i), part_b, &part_ca, &part_cb, check_args);
1489 } else if (is_ex_exactly_of_type(b, mul)) {
1490 if (is_ex_exactly_of_type(a, mul) && a.nops() > b.nops())
1496 for (unsigned i=0; i<b.nops(); i++) {
1497 ex part_ca, part_cb;
1498 g *= gcd(part_a, b.op(i), &part_ca, &part_cb, check_args);
1510 // Input polynomials of the form poly^n are sometimes also trivial
1511 if (is_ex_exactly_of_type(a, power)) {
1513 if (is_ex_exactly_of_type(b, power)) {
1514 if (p.is_equal(b.op(0))) {
1515 // a = p^n, b = p^m, gcd = p^min(n, m)
1516 ex exp_a = a.op(1), exp_b = b.op(1);
1517 if (exp_a < exp_b) {
1521 *cb = power(p, exp_b - exp_a);
1522 return power(p, exp_a);
1525 *ca = power(p, exp_a - exp_b);
1528 return power(p, exp_b);
1532 if (p.is_equal(b)) {
1533 // a = p^n, b = p, gcd = p
1535 *ca = power(p, a.op(1) - 1);
1541 } else if (is_ex_exactly_of_type(b, power)) {
1543 if (p.is_equal(a)) {
1544 // a = p, b = p^n, gcd = p
1548 *cb = power(p, b.op(1) - 1);
1554 // Some trivial cases
1555 ex aex = a.expand(), bex = b.expand();
1556 if (aex.is_zero()) {
1563 if (bex.is_zero()) {
1570 if (aex.is_equal(_ex1()) || bex.is_equal(_ex1())) {
1578 if (a.is_equal(b)) {
1587 // Gather symbol statistics
1588 sym_desc_vec sym_stats;
1589 get_symbol_stats(a, b, sym_stats);
1591 // The symbol with least degree is our main variable
1592 sym_desc_vec::const_iterator var = sym_stats.begin();
1593 const symbol &x = *(var->sym);
1595 // Cancel trivial common factor
1596 int ldeg_a = var->ldeg_a;
1597 int ldeg_b = var->ldeg_b;
1598 int min_ldeg = std::min(ldeg_a,ldeg_b);
1600 ex common = power(x, min_ldeg);
1601 //std::clog << "trivial common factor " << common << std::endl;
1602 return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1605 // Try to eliminate variables
1606 if (var->deg_a == 0) {
1607 //std::clog << "eliminating variable " << x << " from b" << std::endl;
1608 ex c = bex.content(x);
1609 ex g = gcd(aex, c, ca, cb, false);
1611 *cb *= bex.unit(x) * bex.primpart(x, c);
1613 } else if (var->deg_b == 0) {
1614 //std::clog << "eliminating variable " << x << " from a" << std::endl;
1615 ex c = aex.content(x);
1616 ex g = gcd(c, bex, ca, cb, false);
1618 *ca *= aex.unit(x) * aex.primpart(x, c);
1624 // Try heuristic algorithm first, fall back to PRS if that failed
1626 g = heur_gcd(aex, bex, ca, cb, var);
1627 } catch (gcdheu_failed) {
1630 if (is_ex_exactly_of_type(g, fail)) {
1631 //std::clog << "heuristics failed" << std::endl;
1636 // g = heur_gcd(aex, bex, ca, cb, var);
1637 // g = eu_gcd(aex, bex, &x);
1638 // g = euprem_gcd(aex, bex, &x);
1639 // g = peu_gcd(aex, bex, &x);
1640 // g = red_gcd(aex, bex, &x);
1641 g = sr_gcd(aex, bex, var);
1642 if (g.is_equal(_ex1())) {
1643 // Keep cofactors factored if possible
1650 divide(aex, g, *ca, false);
1652 divide(bex, g, *cb, false);
1656 if (g.is_equal(_ex1())) {
1657 // Keep cofactors factored if possible
1669 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1671 * @param a first multivariate polynomial
1672 * @param b second multivariate polynomial
1673 * @param check_args check whether a and b are polynomials with rational
1674 * coefficients (defaults to "true")
1675 * @return the LCM as a new expression */
1676 ex lcm(const ex &a, const ex &b, bool check_args)
1678 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
1679 return lcm(ex_to<numeric>(a), ex_to<numeric>(b));
1680 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
1681 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1684 ex g = gcd(a, b, &ca, &cb, false);
1690 * Square-free factorization
1693 /** Compute square-free factorization of multivariate polynomial a(x) using
1694 * YunĀ“s algorithm. Used internally by sqrfree().
1696 * @param a multivariate polynomial over Z[X], treated here as univariate
1698 * @param x variable to factor in
1699 * @return vector of factors sorted in ascending degree */
1700 static exvector sqrfree_yun(const ex &a, const symbol &x)
1706 if (g.is_equal(_ex1())) {
1717 } while (!z.is_zero());
1720 /** Compute square-free factorization of multivariate polynomial in Q[X].
1722 * @param a multivariate polynomial over Q[X]
1723 * @param x lst of variables to factor in, may be left empty for autodetection
1724 * @return polynomail a in square-free factored form. */
1725 ex sqrfree(const ex &a, const lst &l)
1727 if (is_ex_of_type(a,numeric) || // algorithm does not trap a==0
1728 is_ex_of_type(a,symbol)) // shortcut
1730 // If no lst of variables to factorize in was specified we have to
1731 // invent one now. Maybe one can optimize here by reversing the order
1732 // or so, I don't know.
1736 get_symbol_stats(a, _ex0(), sdv);
1737 for (sym_desc_vec::iterator it=sdv.begin(); it!=sdv.end(); ++it)
1738 args.append(*it->sym);
1742 // Find the symbol to factor in at this stage
1743 if (!is_ex_of_type(args.op(0), symbol))
1744 throw (std::runtime_error("sqrfree(): invalid factorization variable"));
1745 const symbol x = ex_to<symbol>(args.op(0));
1746 // convert the argument from something in Q[X] to something in Z[X]
1747 numeric lcm = lcm_of_coefficients_denominators(a);
1748 ex tmp = multiply_lcm(a,lcm);
1750 exvector factors = sqrfree_yun(tmp,x);
1751 // construct the next list of symbols with the first element popped
1753 for (int i=1; i<args.nops(); ++i)
1754 newargs.append(args.op(i));
1755 // recurse down the factors in remaining vars
1756 if (newargs.nops()>0) {
1757 for (exvector::iterator i=factors.begin(); i!=factors.end(); ++i)
1758 *i = sqrfree(*i, newargs);
1760 // Done with recursion, now construct the final result
1762 exvector::iterator it = factors.begin();
1763 for (int p = 1; it!=factors.end(); ++it, ++p)
1764 result *= power(*it, p);
1765 // Yun's algorithm does not account for constant factors. (For
1766 // univariate polynomials it works only in the monic case.) We can
1767 // correct this by inserting what has been lost back into the result:
1768 result = result * quo(tmp, result, x);
1769 return result * lcm.inverse();
1774 * Normal form of rational functions
1778 * Note: The internal normal() functions (= basic::normal() and overloaded
1779 * functions) all return lists of the form {numerator, denominator}. This
1780 * is to get around mul::eval()'s automatic expansion of numeric coefficients.
1781 * E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
1782 * the information that (a+b) is the numerator and 3 is the denominator.
1785 /** Create a symbol for replacing the expression "e" (or return a previously
1786 * assigned symbol). The symbol is appended to sym_lst and returned, the
1787 * expression is appended to repl_lst.
1788 * @see ex::normal */
1789 static ex replace_with_symbol(const ex &e, lst &sym_lst, lst &repl_lst)
1791 // Expression already in repl_lst? Then return the assigned symbol
1792 for (unsigned i=0; i<repl_lst.nops(); i++)
1793 if (repl_lst.op(i).is_equal(e))
1794 return sym_lst.op(i);
1796 // Otherwise create new symbol and add to list, taking care that the
1797 // replacement expression doesn't contain symbols from the sym_lst
1798 // because subs() is not recursive
1801 ex e_replaced = e.subs(sym_lst, repl_lst);
1803 repl_lst.append(e_replaced);
1807 /** Create a symbol for replacing the expression "e" (or return a previously
1808 * assigned symbol). An expression of the form "symbol == expression" is added
1809 * to repl_lst and the symbol is returned.
1810 * @see ex::to_rational */
1811 static ex replace_with_symbol(const ex &e, lst &repl_lst)
1813 // Expression already in repl_lst? Then return the assigned symbol
1814 for (unsigned i=0; i<repl_lst.nops(); i++)
1815 if (repl_lst.op(i).op(1).is_equal(e))
1816 return repl_lst.op(i).op(0);
1818 // Otherwise create new symbol and add to list, taking care that the
1819 // replacement expression doesn't contain symbols from the sym_lst
1820 // because subs() is not recursive
1823 ex e_replaced = e.subs(repl_lst);
1824 repl_lst.append(es == e_replaced);
1828 /** Default implementation of ex::normal(). It replaces the object with a
1830 * @see ex::normal */
1831 ex basic::normal(lst &sym_lst, lst &repl_lst, int level) const
1833 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1837 /** Implementation of ex::normal() for symbols. This returns the unmodified symbol.
1838 * @see ex::normal */
1839 ex symbol::normal(lst &sym_lst, lst &repl_lst, int level) const
1841 return (new lst(*this, _ex1()))->setflag(status_flags::dynallocated);
1845 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1846 * into re+I*im and replaces I and non-rational real numbers with a temporary
1848 * @see ex::normal */
1849 ex numeric::normal(lst &sym_lst, lst &repl_lst, int level) const
1851 numeric num = numer();
1854 if (num.is_real()) {
1855 if (!num.is_integer())
1856 numex = replace_with_symbol(numex, sym_lst, repl_lst);
1858 numeric re = num.real(), im = num.imag();
1859 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, sym_lst, repl_lst);
1860 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, sym_lst, repl_lst);
1861 numex = re_ex + im_ex * replace_with_symbol(I, sym_lst, repl_lst);
1864 // Denominator is always a real integer (see numeric::denom())
1865 return (new lst(numex, denom()))->setflag(status_flags::dynallocated);
1869 /** Fraction cancellation.
1870 * @param n numerator
1871 * @param d denominator
1872 * @return cancelled fraction {n, d} as a list */
1873 static ex frac_cancel(const ex &n, const ex &d)
1877 numeric pre_factor = _num1();
1879 //std::clog << "frac_cancel num = " << num << ", den = " << den << std::endl;
1881 // Handle trivial case where denominator is 1
1882 if (den.is_equal(_ex1()))
1883 return (new lst(num, den))->setflag(status_flags::dynallocated);
1885 // Handle special cases where numerator or denominator is 0
1887 return (new lst(num, _ex1()))->setflag(status_flags::dynallocated);
1888 if (den.expand().is_zero())
1889 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
1891 // Bring numerator and denominator to Z[X] by multiplying with
1892 // LCM of all coefficients' denominators
1893 numeric num_lcm = lcm_of_coefficients_denominators(num);
1894 numeric den_lcm = lcm_of_coefficients_denominators(den);
1895 num = multiply_lcm(num, num_lcm);
1896 den = multiply_lcm(den, den_lcm);
1897 pre_factor = den_lcm / num_lcm;
1899 // Cancel GCD from numerator and denominator
1901 if (gcd(num, den, &cnum, &cden, false) != _ex1()) {
1906 // Make denominator unit normal (i.e. coefficient of first symbol
1907 // as defined by get_first_symbol() is made positive)
1909 if (get_first_symbol(den, x)) {
1910 GINAC_ASSERT(is_ex_exactly_of_type(den.unit(*x),numeric));
1911 if (ex_to<numeric>(den.unit(*x)).is_negative()) {
1917 // Return result as list
1918 //std::clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << std::endl;
1919 return (new lst(num * pre_factor.numer(), den * pre_factor.denom()))->setflag(status_flags::dynallocated);
1923 /** Implementation of ex::normal() for a sum. It expands terms and performs
1924 * fractional addition.
1925 * @see ex::normal */
1926 ex add::normal(lst &sym_lst, lst &repl_lst, int level) const
1929 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1930 else if (level == -max_recursion_level)
1931 throw(std::runtime_error("max recursion level reached"));
1933 // Normalize children and split each one into numerator and denominator
1934 exvector nums, dens;
1935 nums.reserve(seq.size()+1);
1936 dens.reserve(seq.size()+1);
1937 epvector::const_iterator it = seq.begin(), itend = seq.end();
1938 while (it != itend) {
1939 ex n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1);
1940 nums.push_back(n.op(0));
1941 dens.push_back(n.op(1));
1944 ex n = overall_coeff.bp->normal(sym_lst, repl_lst, level-1);
1945 nums.push_back(n.op(0));
1946 dens.push_back(n.op(1));
1947 GINAC_ASSERT(nums.size() == dens.size());
1949 // Now, nums is a vector of all numerators and dens is a vector of
1951 //std::clog << "add::normal uses " << nums.size() << " summands:\n";
1953 // Add fractions sequentially
1954 exvector::const_iterator num_it = nums.begin(), num_itend = nums.end();
1955 exvector::const_iterator den_it = dens.begin(), den_itend = dens.end();
1956 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
1957 ex num = *num_it++, den = *den_it++;
1958 while (num_it != num_itend) {
1959 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
1960 ex next_num = *num_it++, next_den = *den_it++;
1962 // Trivially add sequences of fractions with identical denominators
1963 while ((den_it != den_itend) && next_den.is_equal(*den_it)) {
1964 next_num += *num_it;
1968 // Additiion of two fractions, taking advantage of the fact that
1969 // the heuristic GCD algorithm computes the cofactors at no extra cost
1970 ex co_den1, co_den2;
1971 ex g = gcd(den, next_den, &co_den1, &co_den2, false);
1972 num = ((num * co_den2) + (next_num * co_den1)).expand();
1973 den *= co_den2; // this is the lcm(den, next_den)
1975 //std::clog << " common denominator = " << den << std::endl;
1977 // Cancel common factors from num/den
1978 return frac_cancel(num, den);
1982 /** Implementation of ex::normal() for a product. It cancels common factors
1984 * @see ex::normal() */
1985 ex mul::normal(lst &sym_lst, lst &repl_lst, int level) const
1988 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1989 else if (level == -max_recursion_level)
1990 throw(std::runtime_error("max recursion level reached"));
1992 // Normalize children, separate into numerator and denominator
1996 epvector::const_iterator it = seq.begin(), itend = seq.end();
1997 while (it != itend) {
1998 n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1);
2003 n = overall_coeff.bp->normal(sym_lst, repl_lst, level-1);
2007 // Perform fraction cancellation
2008 return frac_cancel(num, den);
2012 /** Implementation of ex::normal() for powers. It normalizes the basis,
2013 * distributes integer exponents to numerator and denominator, and replaces
2014 * non-integer powers by temporary symbols.
2015 * @see ex::normal */
2016 ex power::normal(lst &sym_lst, lst &repl_lst, int level) const
2019 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
2020 else if (level == -max_recursion_level)
2021 throw(std::runtime_error("max recursion level reached"));
2023 // Normalize basis and exponent (exponent gets reassembled)
2024 ex n_basis = basis.bp->normal(sym_lst, repl_lst, level-1);
2025 ex n_exponent = exponent.bp->normal(sym_lst, repl_lst, level-1);
2026 n_exponent = n_exponent.op(0) / n_exponent.op(1);
2028 if (n_exponent.info(info_flags::integer)) {
2030 if (n_exponent.info(info_flags::positive)) {
2032 // (a/b)^n -> {a^n, b^n}
2033 return (new lst(power(n_basis.op(0), n_exponent), power(n_basis.op(1), n_exponent)))->setflag(status_flags::dynallocated);
2035 } else if (n_exponent.info(info_flags::negative)) {
2037 // (a/b)^-n -> {b^n, a^n}
2038 return (new lst(power(n_basis.op(1), -n_exponent), power(n_basis.op(0), -n_exponent)))->setflag(status_flags::dynallocated);
2043 if (n_exponent.info(info_flags::positive)) {
2045 // (a/b)^x -> {sym((a/b)^x), 1}
2046 return (new lst(replace_with_symbol(power(n_basis.op(0) / n_basis.op(1), n_exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
2048 } else if (n_exponent.info(info_flags::negative)) {
2050 if (n_basis.op(1).is_equal(_ex1())) {
2052 // a^-x -> {1, sym(a^x)}
2053 return (new lst(_ex1(), replace_with_symbol(power(n_basis.op(0), -n_exponent), sym_lst, repl_lst)))->setflag(status_flags::dynallocated);
2057 // (a/b)^-x -> {sym((b/a)^x), 1}
2058 return (new lst(replace_with_symbol(power(n_basis.op(1) / n_basis.op(0), -n_exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
2061 } else { // n_exponent not numeric
2063 // (a/b)^x -> {sym((a/b)^x, 1}
2064 return (new lst(replace_with_symbol(power(n_basis.op(0) / n_basis.op(1), n_exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
2070 /** Implementation of ex::normal() for pseries. It normalizes each coefficient
2071 * and replaces the series by a temporary symbol.
2072 * @see ex::normal */
2073 ex pseries::normal(lst &sym_lst, lst &repl_lst, int level) const
2076 for (epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i) {
2077 ex restexp = i->rest.normal();
2078 if (!restexp.is_zero())
2079 newseq.push_back(expair(restexp, i->coeff));
2081 ex n = pseries(relational(var,point), newseq);
2082 return (new lst(replace_with_symbol(n, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
2086 /** Implementation of ex::normal() for relationals. It normalizes both sides.
2087 * @see ex::normal */
2088 ex relational::normal(lst &sym_lst, lst &repl_lst, int level) const
2090 return (new lst(relational(lh.normal(), rh.normal(), o), _ex1()))->setflag(status_flags::dynallocated);
2094 /** Normalization of rational functions.
2095 * This function converts an expression to its normal form
2096 * "numerator/denominator", where numerator and denominator are (relatively
2097 * prime) polynomials. Any subexpressions which are not rational functions
2098 * (like non-rational numbers, non-integer powers or functions like sin(),
2099 * cos() etc.) are replaced by temporary symbols which are re-substituted by
2100 * the (normalized) subexpressions before normal() returns (this way, any
2101 * expression can be treated as a rational function). normal() is applied
2102 * recursively to arguments of functions etc.
2104 * @param level maximum depth of recursion
2105 * @return normalized expression */
2106 ex ex::normal(int level) const
2108 lst sym_lst, repl_lst;
2110 ex e = bp->normal(sym_lst, repl_lst, level);
2111 GINAC_ASSERT(is_ex_of_type(e, lst));
2113 // Re-insert replaced symbols
2114 if (sym_lst.nops() > 0)
2115 e = e.subs(sym_lst, repl_lst);
2117 // Convert {numerator, denominator} form back to fraction
2118 return e.op(0) / e.op(1);
2121 /** Get numerator of an expression. If the expression is not of the normal
2122 * form "numerator/denominator", it is first converted to this form and
2123 * then the numerator is returned.
2126 * @return numerator */
2127 ex ex::numer(void) const
2129 lst sym_lst, repl_lst;
2131 ex e = bp->normal(sym_lst, repl_lst, 0);
2132 GINAC_ASSERT(is_ex_of_type(e, lst));
2134 // Re-insert replaced symbols
2135 if (sym_lst.nops() > 0)
2136 return e.op(0).subs(sym_lst, repl_lst);
2141 /** Get denominator of an expression. If the expression is not of the normal
2142 * form "numerator/denominator", it is first converted to this form and
2143 * then the denominator is returned.
2146 * @return denominator */
2147 ex ex::denom(void) const
2149 lst sym_lst, repl_lst;
2151 ex e = bp->normal(sym_lst, repl_lst, 0);
2152 GINAC_ASSERT(is_ex_of_type(e, lst));
2154 // Re-insert replaced symbols
2155 if (sym_lst.nops() > 0)
2156 return e.op(1).subs(sym_lst, repl_lst);
2161 /** Get numerator and denominator of an expression. If the expresison is not
2162 * of the normal form "numerator/denominator", it is first converted to this
2163 * form and then a list [numerator, denominator] is returned.
2166 * @return a list [numerator, denominator] */
2167 ex ex::numer_denom(void) const
2169 lst sym_lst, repl_lst;
2171 ex e = bp->normal(sym_lst, repl_lst, 0);
2172 GINAC_ASSERT(is_ex_of_type(e, lst));
2174 // Re-insert replaced symbols
2175 if (sym_lst.nops() > 0)
2176 return e.subs(sym_lst, repl_lst);
2182 /** Default implementation of ex::to_rational(). It replaces the object with a
2184 * @see ex::to_rational */
2185 ex basic::to_rational(lst &repl_lst) const
2187 return replace_with_symbol(*this, repl_lst);
2191 /** Implementation of ex::to_rational() for symbols. This returns the
2192 * unmodified symbol.
2193 * @see ex::to_rational */
2194 ex symbol::to_rational(lst &repl_lst) const
2200 /** Implementation of ex::to_rational() for a numeric. It splits complex
2201 * numbers into re+I*im and replaces I and non-rational real numbers with a
2203 * @see ex::to_rational */
2204 ex numeric::to_rational(lst &repl_lst) const
2208 return replace_with_symbol(*this, repl_lst);
2210 numeric re = real();
2211 numeric im = imag();
2212 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl_lst);
2213 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl_lst);
2214 return re_ex + im_ex * replace_with_symbol(I, repl_lst);
2220 /** Implementation of ex::to_rational() for powers. It replaces non-integer
2221 * powers by temporary symbols.
2222 * @see ex::to_rational */
2223 ex power::to_rational(lst &repl_lst) const
2225 if (exponent.info(info_flags::integer))
2226 return power(basis.to_rational(repl_lst), exponent);
2228 return replace_with_symbol(*this, repl_lst);
2232 /** Implementation of ex::to_rational() for expairseqs.
2233 * @see ex::to_rational */
2234 ex expairseq::to_rational(lst &repl_lst) const
2237 s.reserve(seq.size());
2238 for (epvector::const_iterator it=seq.begin(); it!=seq.end(); ++it) {
2239 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*it).to_rational(repl_lst)));
2240 // s.push_back(combine_ex_with_coeff_to_pair((*it).rest.to_rational(repl_lst),
2242 ex oc = overall_coeff.to_rational(repl_lst);
2243 if (oc.info(info_flags::numeric))
2244 return thisexpairseq(s, overall_coeff);
2245 else s.push_back(combine_ex_with_coeff_to_pair(oc,_ex1()));
2246 return thisexpairseq(s, default_overall_coeff());
2250 /** Rationalization of non-rational functions.
2251 * This function converts a general expression to a rational polynomial
2252 * by replacing all non-rational subexpressions (like non-rational numbers,
2253 * non-integer powers or functions like sin(), cos() etc.) to temporary
2254 * symbols. This makes it possible to use functions like gcd() and divide()
2255 * on non-rational functions by applying to_rational() on the arguments,
2256 * calling the desired function and re-substituting the temporary symbols
2257 * in the result. To make the last step possible, all temporary symbols and
2258 * their associated expressions are collected in the list specified by the
2259 * repl_lst parameter in the form {symbol == expression}, ready to be passed
2260 * as an argument to ex::subs().
2262 * @param repl_lst collects a list of all temporary symbols and their replacements
2263 * @return rationalized expression */
2264 ex ex::to_rational(lst &repl_lst) const
2266 return bp->to_rational(repl_lst);
2270 } // namespace GiNaC