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"
42 #include "relational.h"
49 // If comparing expressions (ex::compare()) is fast, you can set this to 1.
50 // Some routines like quo(), rem() and gcd() will then return a quick answer
51 // when they are called with two identical arguments.
52 #define FAST_COMPARE 1
54 // Set this if you want divide_in_z() to use remembering
55 #define USE_REMEMBER 0
57 // Set this if you want divide_in_z() to use trial division followed by
58 // polynomial interpolation (always slower except for completely dense
60 #define USE_TRIAL_DIVISION 0
62 // Set this to enable some statistical output for the GCD routines
67 // Statistics variables
68 static int gcd_called = 0;
69 static int sr_gcd_called = 0;
70 static int heur_gcd_called = 0;
71 static int heur_gcd_failed = 0;
73 // Print statistics at end of program
74 static struct _stat_print {
77 cout << "gcd() called " << gcd_called << " times\n";
78 cout << "sr_gcd() called " << sr_gcd_called << " times\n";
79 cout << "heur_gcd() called " << heur_gcd_called << " times\n";
80 cout << "heur_gcd() failed " << heur_gcd_failed << " times\n";
86 /** Return pointer to first symbol found in expression. Due to GiNaCĀ“s
87 * internal ordering of terms, it may not be obvious which symbol this
88 * function returns for a given expression.
90 * @param e expression to search
91 * @param x pointer to first symbol found (returned)
92 * @return "false" if no symbol was found, "true" otherwise */
93 static bool get_first_symbol(const ex &e, const symbol *&x)
95 if (is_ex_exactly_of_type(e, symbol)) {
96 x = static_cast<symbol *>(e.bp);
98 } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
99 for (unsigned i=0; i<e.nops(); i++)
100 if (get_first_symbol(e.op(i), x))
102 } else if (is_ex_exactly_of_type(e, power)) {
103 if (get_first_symbol(e.op(0), x))
111 * Statistical information about symbols in polynomials
114 /** This structure holds information about the highest and lowest degrees
115 * in which a symbol appears in two multivariate polynomials "a" and "b".
116 * A vector of these structures with information about all symbols in
117 * two polynomials can be created with the function get_symbol_stats().
119 * @see get_symbol_stats */
121 /** Pointer to symbol */
124 /** Highest degree of symbol in polynomial "a" */
127 /** Highest degree of symbol in polynomial "b" */
130 /** Lowest degree of symbol in polynomial "a" */
133 /** Lowest degree of symbol in polynomial "b" */
136 /** Maximum of deg_a and deg_b (Used for sorting) */
139 /** Maximum number of terms of leading coefficient of symbol in both polynomials */
142 /** Commparison operator for sorting */
143 bool operator<(const sym_desc &x) const
145 if (max_deg == x.max_deg)
146 return max_lcnops < x.max_lcnops;
148 return max_deg < x.max_deg;
152 // Vector of sym_desc structures
153 typedef std::vector<sym_desc> sym_desc_vec;
155 // Add symbol the sym_desc_vec (used internally by get_symbol_stats())
156 static void add_symbol(const symbol *s, sym_desc_vec &v)
158 sym_desc_vec::iterator it = v.begin(), itend = v.end();
159 while (it != itend) {
160 if (it->sym->compare(*s) == 0) // If it's already in there, don't add it a second time
169 // Collect all symbols of an expression (used internally by get_symbol_stats())
170 static void collect_symbols(const ex &e, sym_desc_vec &v)
172 if (is_ex_exactly_of_type(e, symbol)) {
173 add_symbol(static_cast<symbol *>(e.bp), v);
174 } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
175 for (unsigned i=0; i<e.nops(); i++)
176 collect_symbols(e.op(i), v);
177 } else if (is_ex_exactly_of_type(e, power)) {
178 collect_symbols(e.op(0), v);
182 /** Collect statistical information about symbols in polynomials.
183 * This function fills in a vector of "sym_desc" structs which contain
184 * information about the highest and lowest degrees of all symbols that
185 * appear in two polynomials. The vector is then sorted by minimum
186 * degree (lowest to highest). The information gathered by this
187 * function is used by the GCD routines to identify trivial factors
188 * and to determine which variable to choose as the main variable
189 * for GCD computation.
191 * @param a first multivariate polynomial
192 * @param b second multivariate polynomial
193 * @param v vector of sym_desc structs (filled in) */
194 static void get_symbol_stats(const ex &a, const ex &b, sym_desc_vec &v)
196 collect_symbols(a.eval(), v); // eval() to expand assigned symbols
197 collect_symbols(b.eval(), v);
198 sym_desc_vec::iterator it = v.begin(), itend = v.end();
199 while (it != itend) {
200 int deg_a = a.degree(*(it->sym));
201 int deg_b = b.degree(*(it->sym));
204 it->max_deg = std::max(deg_a, deg_b);
205 it->max_lcnops = std::max(a.lcoeff(*(it->sym)).nops(), b.lcoeff(*(it->sym)).nops());
206 it->ldeg_a = a.ldegree(*(it->sym));
207 it->ldeg_b = b.ldegree(*(it->sym));
210 sort(v.begin(), v.end());
212 std::clog << "Symbols:\n";
213 it = v.begin(); itend = v.end();
214 while (it != itend) {
215 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;
216 std::clog << " lcoeff_a=" << a.lcoeff(*(it->sym)) << ", lcoeff_b=" << b.lcoeff(*(it->sym)) << endl;
224 * Computation of LCM of denominators of coefficients of a polynomial
227 // Compute LCM of denominators of coefficients by going through the
228 // expression recursively (used internally by lcm_of_coefficients_denominators())
229 static numeric lcmcoeff(const ex &e, const numeric &l)
231 if (e.info(info_flags::rational))
232 return lcm(ex_to_numeric(e).denom(), l);
233 else if (is_ex_exactly_of_type(e, add)) {
235 for (unsigned i=0; i<e.nops(); i++)
236 c = lcmcoeff(e.op(i), c);
238 } else if (is_ex_exactly_of_type(e, mul)) {
240 for (unsigned i=0; i<e.nops(); i++)
241 c *= lcmcoeff(e.op(i), _num1());
243 } else if (is_ex_exactly_of_type(e, power)) {
244 if (is_ex_exactly_of_type(e.op(0), symbol))
247 return pow(lcmcoeff(e.op(0), l), ex_to_numeric(e.op(1)));
252 /** Compute LCM of denominators of coefficients of a polynomial.
253 * Given a polynomial with rational coefficients, this function computes
254 * the LCM of the denominators of all coefficients. This can be used
255 * to bring a polynomial from Q[X] to Z[X].
257 * @param e multivariate polynomial (need not be expanded)
258 * @return LCM of denominators of coefficients */
259 static numeric lcm_of_coefficients_denominators(const ex &e)
261 return lcmcoeff(e, _num1());
264 /** Bring polynomial from Q[X] to Z[X] by multiplying in the previously
265 * determined LCM of the coefficient's denominators.
267 * @param e multivariate polynomial (need not be expanded)
268 * @param lcm LCM to multiply in */
269 static ex multiply_lcm(const ex &e, const numeric &lcm)
271 if (is_ex_exactly_of_type(e, mul)) {
273 numeric lcm_accum = _num1();
274 for (unsigned i=0; i<e.nops(); i++) {
275 numeric op_lcm = lcmcoeff(e.op(i), _num1());
276 c *= multiply_lcm(e.op(i), op_lcm);
279 c *= lcm / lcm_accum;
281 } else if (is_ex_exactly_of_type(e, add)) {
283 for (unsigned i=0; i<e.nops(); i++)
284 c += multiply_lcm(e.op(i), lcm);
286 } else if (is_ex_exactly_of_type(e, power)) {
287 if (is_ex_exactly_of_type(e.op(0), symbol))
290 return pow(multiply_lcm(e.op(0), lcm.power(ex_to_numeric(e.op(1)).inverse())), e.op(1));
296 /** Compute the integer content (= GCD of all numeric coefficients) of an
297 * expanded polynomial.
299 * @param e expanded polynomial
300 * @return integer content */
301 numeric ex::integer_content(void) const
304 return bp->integer_content();
307 numeric basic::integer_content(void) const
312 numeric numeric::integer_content(void) const
317 numeric add::integer_content(void) const
319 epvector::const_iterator it = seq.begin();
320 epvector::const_iterator itend = seq.end();
322 while (it != itend) {
323 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
324 GINAC_ASSERT(is_ex_exactly_of_type(it->coeff,numeric));
325 c = gcd(ex_to_numeric(it->coeff), c);
328 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
329 c = gcd(ex_to_numeric(overall_coeff),c);
333 numeric mul::integer_content(void) const
335 #ifdef DO_GINAC_ASSERT
336 epvector::const_iterator it = seq.begin();
337 epvector::const_iterator itend = seq.end();
338 while (it != itend) {
339 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
342 #endif // def DO_GINAC_ASSERT
343 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
344 return abs(ex_to_numeric(overall_coeff));
349 * Polynomial quotients and remainders
352 /** Quotient q(x) of polynomials a(x) and b(x) in Q[x].
353 * It satisfies a(x)=b(x)*q(x)+r(x).
355 * @param a first polynomial in x (dividend)
356 * @param b second polynomial in x (divisor)
357 * @param x a and b are polynomials in x
358 * @param check_args check whether a and b are polynomials with rational
359 * coefficients (defaults to "true")
360 * @return quotient of a and b in Q[x] */
361 ex quo(const ex &a, const ex &b, const symbol &x, bool check_args)
364 throw(std::overflow_error("quo: division by zero"));
365 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
371 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
372 throw(std::invalid_argument("quo: arguments must be polynomials over the rationals"));
374 // Polynomial long division
379 int bdeg = b.degree(x);
380 int rdeg = r.degree(x);
381 ex blcoeff = b.expand().coeff(x, bdeg);
382 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
383 while (rdeg >= bdeg) {
384 ex term, rcoeff = r.coeff(x, rdeg);
385 if (blcoeff_is_numeric)
386 term = rcoeff / blcoeff;
388 if (!divide(rcoeff, blcoeff, term, false))
389 return *new ex(fail());
391 term *= power(x, rdeg - bdeg);
393 r -= (term * b).expand();
402 /** Remainder r(x) of polynomials a(x) and b(x) in Q[x].
403 * It satisfies a(x)=b(x)*q(x)+r(x).
405 * @param a first polynomial in x (dividend)
406 * @param b second polynomial in x (divisor)
407 * @param x a and b are polynomials in x
408 * @param check_args check whether a and b are polynomials with rational
409 * coefficients (defaults to "true")
410 * @return remainder of a(x) and b(x) in Q[x] */
411 ex rem(const ex &a, const ex &b, const symbol &x, bool check_args)
414 throw(std::overflow_error("rem: division by zero"));
415 if (is_ex_exactly_of_type(a, numeric)) {
416 if (is_ex_exactly_of_type(b, numeric))
425 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
426 throw(std::invalid_argument("rem: arguments must be polynomials over the rationals"));
428 // Polynomial long division
432 int bdeg = b.degree(x);
433 int rdeg = r.degree(x);
434 ex blcoeff = b.expand().coeff(x, bdeg);
435 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
436 while (rdeg >= bdeg) {
437 ex term, rcoeff = r.coeff(x, rdeg);
438 if (blcoeff_is_numeric)
439 term = rcoeff / blcoeff;
441 if (!divide(rcoeff, blcoeff, term, false))
442 return *new ex(fail());
444 term *= power(x, rdeg - bdeg);
445 r -= (term * b).expand();
454 /** Pseudo-remainder of polynomials a(x) and b(x) in Z[x].
456 * @param a first polynomial in x (dividend)
457 * @param b second polynomial in x (divisor)
458 * @param x a and b are polynomials in x
459 * @param check_args check whether a and b are polynomials with rational
460 * coefficients (defaults to "true")
461 * @return pseudo-remainder of a(x) and b(x) in Z[x] */
462 ex prem(const ex &a, const ex &b, const symbol &x, bool check_args)
465 throw(std::overflow_error("prem: division by zero"));
466 if (is_ex_exactly_of_type(a, numeric)) {
467 if (is_ex_exactly_of_type(b, numeric))
472 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
473 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
475 // Polynomial long division
478 int rdeg = r.degree(x);
479 int bdeg = eb.degree(x);
482 blcoeff = eb.coeff(x, bdeg);
486 eb -= blcoeff * power(x, bdeg);
490 int delta = rdeg - bdeg + 1, i = 0;
491 while (rdeg >= bdeg && !r.is_zero()) {
492 ex rlcoeff = r.coeff(x, rdeg);
493 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
497 r -= rlcoeff * power(x, rdeg);
498 r = (blcoeff * r).expand() - term;
502 return power(blcoeff, delta - i) * r;
506 /** Sparse pseudo-remainder of polynomials a(x) and b(x) in Z[x].
508 * @param a first polynomial in x (dividend)
509 * @param b second polynomial in x (divisor)
510 * @param x a and b are polynomials in x
511 * @param check_args check whether a and b are polynomials with rational
512 * coefficients (defaults to "true")
513 * @return sparse pseudo-remainder of a(x) and b(x) in Z[x] */
515 ex sprem(const ex &a, const ex &b, const symbol &x, bool check_args)
518 throw(std::overflow_error("prem: division by zero"));
519 if (is_ex_exactly_of_type(a, numeric)) {
520 if (is_ex_exactly_of_type(b, numeric))
525 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
526 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
528 // Polynomial long division
531 int rdeg = r.degree(x);
532 int bdeg = eb.degree(x);
535 blcoeff = eb.coeff(x, bdeg);
539 eb -= blcoeff * power(x, bdeg);
543 while (rdeg >= bdeg && !r.is_zero()) {
544 ex rlcoeff = r.coeff(x, rdeg);
545 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
549 r -= rlcoeff * power(x, rdeg);
550 r = (blcoeff * r).expand() - term;
557 /** Exact polynomial division of a(X) by b(X) in Q[X].
559 * @param a first multivariate polynomial (dividend)
560 * @param b second multivariate polynomial (divisor)
561 * @param q quotient (returned)
562 * @param check_args check whether a and b are polynomials with rational
563 * coefficients (defaults to "true")
564 * @return "true" when exact division succeeds (quotient returned in q),
565 * "false" otherwise */
566 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
570 throw(std::overflow_error("divide: division by zero"));
573 if (is_ex_exactly_of_type(b, numeric)) {
576 } else if (is_ex_exactly_of_type(a, numeric))
584 if (check_args && (!a.info(info_flags::rational_polynomial) ||
585 !b.info(info_flags::rational_polynomial)))
586 throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
590 if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
591 throw(std::invalid_argument("invalid expression in divide()"));
593 // Polynomial long division (recursive)
597 int bdeg = b.degree(*x);
598 int rdeg = r.degree(*x);
599 ex blcoeff = b.expand().coeff(*x, bdeg);
600 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
601 while (rdeg >= bdeg) {
602 ex term, rcoeff = r.coeff(*x, rdeg);
603 if (blcoeff_is_numeric)
604 term = rcoeff / blcoeff;
606 if (!divide(rcoeff, blcoeff, term, false))
608 term *= power(*x, rdeg - bdeg);
610 r -= (term * b).expand();
624 typedef std::pair<ex, ex> ex2;
625 typedef std::pair<ex, bool> exbool;
628 bool operator() (const ex2 &p, const ex2 &q) const
630 int cmp = p.first.compare(q.first);
631 return ((cmp<0) || (!(cmp>0) && p.second.compare(q.second)<0));
635 typedef std::map<ex2, exbool, ex2_less> ex2_exbool_remember;
639 /** Exact polynomial division of a(X) by b(X) in Z[X].
640 * This functions works like divide() but the input and output polynomials are
641 * in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
642 * divide(), it doesnĀ“t check whether the input polynomials really are integer
643 * polynomials, so be careful of what you pass in. Also, you have to run
644 * get_symbol_stats() over the input polynomials before calling this function
645 * and pass an iterator to the first element of the sym_desc vector. This
646 * function is used internally by the heur_gcd().
648 * @param a first multivariate polynomial (dividend)
649 * @param b second multivariate polynomial (divisor)
650 * @param q quotient (returned)
651 * @param var iterator to first element of vector of sym_desc structs
652 * @return "true" when exact division succeeds (the quotient is returned in
653 * q), "false" otherwise.
654 * @see get_symbol_stats, heur_gcd */
655 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
659 throw(std::overflow_error("divide_in_z: division by zero"));
660 if (b.is_equal(_ex1())) {
664 if (is_ex_exactly_of_type(a, numeric)) {
665 if (is_ex_exactly_of_type(b, numeric)) {
667 return q.info(info_flags::integer);
680 static ex2_exbool_remember dr_remember;
681 ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
682 if (remembered != dr_remember.end()) {
683 q = remembered->second.first;
684 return remembered->second.second;
689 const symbol *x = var->sym;
692 int adeg = a.degree(*x), bdeg = b.degree(*x);
696 #if USE_TRIAL_DIVISION
698 // Trial division with polynomial interpolation
701 // Compute values at evaluation points 0..adeg
702 vector<numeric> alpha; alpha.reserve(adeg + 1);
703 exvector u; u.reserve(adeg + 1);
704 numeric point = _num0();
706 for (i=0; i<=adeg; i++) {
707 ex bs = b.subs(*x == point);
708 while (bs.is_zero()) {
710 bs = b.subs(*x == point);
712 if (!divide_in_z(a.subs(*x == point), bs, c, var+1))
714 alpha.push_back(point);
720 vector<numeric> rcp; rcp.reserve(adeg + 1);
721 rcp.push_back(_num0());
722 for (k=1; k<=adeg; k++) {
723 numeric product = alpha[k] - alpha[0];
725 product *= alpha[k] - alpha[i];
726 rcp.push_back(product.inverse());
729 // Compute Newton coefficients
730 exvector v; v.reserve(adeg + 1);
732 for (k=1; k<=adeg; k++) {
734 for (i=k-2; i>=0; i--)
735 temp = temp * (alpha[k] - alpha[i]) + v[i];
736 v.push_back((u[k] - temp) * rcp[k]);
739 // Convert from Newton form to standard form
741 for (k=adeg-1; k>=0; k--)
742 c = c * (*x - alpha[k]) + v[k];
744 if (c.degree(*x) == (adeg - bdeg)) {
752 // Polynomial long division (recursive)
758 ex blcoeff = eb.coeff(*x, bdeg);
759 while (rdeg >= bdeg) {
760 ex term, rcoeff = r.coeff(*x, rdeg);
761 if (!divide_in_z(rcoeff, blcoeff, term, var+1))
763 term = (term * power(*x, rdeg - bdeg)).expand();
765 r -= (term * eb).expand();
768 dr_remember[ex2(a, b)] = exbool(q, true);
775 dr_remember[ex2(a, b)] = exbool(q, false);
784 * Separation of unit part, content part and primitive part of polynomials
787 /** Compute unit part (= sign of leading coefficient) of a multivariate
788 * polynomial in Z[x]. The product of unit part, content part, and primitive
789 * part is the polynomial itself.
791 * @param x variable in which to compute the unit part
793 * @see ex::content, ex::primpart */
794 ex ex::unit(const symbol &x) const
796 ex c = expand().lcoeff(x);
797 if (is_ex_exactly_of_type(c, numeric))
798 return c < _ex0() ? _ex_1() : _ex1();
801 if (get_first_symbol(c, y))
804 throw(std::invalid_argument("invalid expression in unit()"));
809 /** Compute content part (= unit normal GCD of all coefficients) of a
810 * multivariate polynomial in Z[x]. The product of unit part, content part,
811 * and primitive part is the polynomial itself.
813 * @param x variable in which to compute the content part
814 * @return content part
815 * @see ex::unit, ex::primpart */
816 ex ex::content(const symbol &x) const
820 if (is_ex_exactly_of_type(*this, numeric))
821 return info(info_flags::negative) ? -*this : *this;
826 // First, try the integer content
827 ex c = e.integer_content();
829 ex lcoeff = r.lcoeff(x);
830 if (lcoeff.info(info_flags::integer))
833 // GCD of all coefficients
834 int deg = e.degree(x);
835 int ldeg = e.ldegree(x);
837 return e.lcoeff(x) / e.unit(x);
839 for (int i=ldeg; i<=deg; i++)
840 c = gcd(e.coeff(x, i), c, NULL, NULL, false);
845 /** Compute primitive part of a multivariate polynomial in Z[x].
846 * The product of unit part, content part, and primitive part is the
849 * @param x variable in which to compute the primitive part
850 * @return primitive part
851 * @see ex::unit, ex::content */
852 ex ex::primpart(const symbol &x) const
856 if (is_ex_exactly_of_type(*this, numeric))
863 if (is_ex_exactly_of_type(c, numeric))
864 return *this / (c * u);
866 return quo(*this, c * u, x, false);
870 /** Compute primitive part of a multivariate polynomial in Z[x] when the
871 * content part is already known. This function is faster in computing the
872 * primitive part than the previous function.
874 * @param x variable in which to compute the primitive part
875 * @param c previously computed content part
876 * @return primitive part */
877 ex ex::primpart(const symbol &x, const ex &c) const
883 if (is_ex_exactly_of_type(*this, numeric))
887 if (is_ex_exactly_of_type(c, numeric))
888 return *this / (c * u);
890 return quo(*this, c * u, x, false);
895 * GCD of multivariate polynomials
898 /** Compute GCD of polynomials in Q[X] using the Euclidean algorithm (not
899 * really suited for multivariate GCDs). This function is only provided for
902 * @param a first multivariate polynomial
903 * @param b second multivariate polynomial
904 * @param x pointer to symbol (main variable) in which to compute the GCD in
905 * @return the GCD as a new expression
908 static ex eu_gcd(const ex &a, const ex &b, const symbol *x)
910 //std::clog << "eu_gcd(" << a << "," << b << ")\n";
912 // Sort c and d so that c has higher degree
914 int adeg = a.degree(*x), bdeg = b.degree(*x);
924 c = c / c.lcoeff(*x);
925 d = d / d.lcoeff(*x);
927 // Euclidean algorithm
930 //std::clog << " d = " << d << endl;
931 r = rem(c, d, *x, false);
933 return d / d.lcoeff(*x);
940 /** Compute GCD of multivariate polynomials using the Euclidean PRS algorithm
941 * with pseudo-remainders ("World's Worst GCD Algorithm", staying in Z[X]).
942 * This function is only provided for testing purposes.
944 * @param a first multivariate polynomial
945 * @param b second multivariate polynomial
946 * @param x pointer to symbol (main variable) in which to compute the GCD in
947 * @return the GCD as a new expression
950 static ex euprem_gcd(const ex &a, const ex &b, const symbol *x)
952 //std::clog << "euprem_gcd(" << a << "," << b << ")\n";
954 // Sort c and d so that c has higher degree
956 int adeg = a.degree(*x), bdeg = b.degree(*x);
965 // Calculate GCD of contents
966 ex gamma = gcd(c.content(*x), d.content(*x), NULL, NULL, false);
968 // Euclidean algorithm with pseudo-remainders
971 //std::clog << " d = " << d << endl;
972 r = prem(c, d, *x, false);
974 return d.primpart(*x) * gamma;
981 /** Compute GCD of multivariate polynomials using the primitive Euclidean
982 * PRS algorithm (complete content removal at each step). This function is
983 * only provided for testing purposes.
985 * @param a first multivariate polynomial
986 * @param b second multivariate polynomial
987 * @param x pointer to symbol (main variable) in which to compute the GCD in
988 * @return the GCD as a new expression
991 static ex peu_gcd(const ex &a, const ex &b, const symbol *x)
993 //std::clog << "peu_gcd(" << a << "," << b << ")\n";
995 // Sort c and d so that c has higher degree
997 int adeg = a.degree(*x), bdeg = b.degree(*x);
1009 // Remove content from c and d, to be attached to GCD later
1010 ex cont_c = c.content(*x);
1011 ex cont_d = d.content(*x);
1012 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1015 c = c.primpart(*x, cont_c);
1016 d = d.primpart(*x, cont_d);
1018 // Euclidean algorithm with content removal
1021 //std::clog << " d = " << d << endl;
1022 r = prem(c, d, *x, false);
1031 /** Compute GCD of multivariate polynomials using the reduced PRS algorithm.
1032 * This function is only provided for testing purposes.
1034 * @param a first multivariate polynomial
1035 * @param b second multivariate polynomial
1036 * @param x pointer to symbol (main variable) in which to compute the GCD in
1037 * @return the GCD as a new expression
1040 static ex red_gcd(const ex &a, const ex &b, const symbol *x)
1042 //std::clog << "red_gcd(" << a << "," << b << ")\n";
1044 // Sort c and d so that c has higher degree
1046 int adeg = a.degree(*x), bdeg = b.degree(*x);
1060 // Remove content from c and d, to be attached to GCD later
1061 ex cont_c = c.content(*x);
1062 ex cont_d = d.content(*x);
1063 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1066 c = c.primpart(*x, cont_c);
1067 d = d.primpart(*x, cont_d);
1069 // First element of divisor sequence
1071 int delta = cdeg - ddeg;
1074 // Calculate polynomial pseudo-remainder
1075 //std::clog << " d = " << d << endl;
1076 r = prem(c, d, *x, false);
1078 return gamma * d.primpart(*x);
1082 if (!divide(r, pow(ri, delta), d, false))
1083 throw(std::runtime_error("invalid expression in red_gcd(), division failed"));
1084 ddeg = d.degree(*x);
1086 if (is_ex_exactly_of_type(r, numeric))
1089 return gamma * r.primpart(*x);
1092 ri = c.expand().lcoeff(*x);
1093 delta = cdeg - ddeg;
1098 /** Compute GCD of multivariate polynomials using the subresultant PRS
1099 * algorithm. This function is used internally by gcd().
1101 * @param a first multivariate polynomial
1102 * @param b second multivariate polynomial
1103 * @param var iterator to first element of vector of sym_desc structs
1104 * @return the GCD as a new expression
1107 static ex sr_gcd(const ex &a, const ex &b, sym_desc_vec::const_iterator var)
1109 //std::clog << "sr_gcd(" << a << "," << b << ")\n";
1114 // The first symbol is our main variable
1115 const symbol &x = *(var->sym);
1117 // Sort c and d so that c has higher degree
1119 int adeg = a.degree(x), bdeg = b.degree(x);
1133 // Remove content from c and d, to be attached to GCD later
1134 ex cont_c = c.content(x);
1135 ex cont_d = d.content(x);
1136 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1139 c = c.primpart(x, cont_c);
1140 d = d.primpart(x, cont_d);
1141 //std::clog << " content " << gamma << " removed, continuing with sr_gcd(" << c << "," << d << ")\n";
1143 // First element of subresultant sequence
1144 ex r = _ex0(), ri = _ex1(), psi = _ex1();
1145 int delta = cdeg - ddeg;
1148 // Calculate polynomial pseudo-remainder
1149 //std::clog << " start of loop, psi = " << psi << ", calculating pseudo-remainder...\n";
1150 //std::clog << " d = " << d << endl;
1151 r = prem(c, d, x, false);
1153 return gamma * d.primpart(x);
1156 //std::clog << " dividing...\n";
1157 if (!divide_in_z(r, ri * pow(psi, delta), d, var))
1158 throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
1161 if (is_ex_exactly_of_type(r, numeric))
1164 return gamma * r.primpart(x);
1167 // Next element of subresultant sequence
1168 //std::clog << " calculating next subresultant...\n";
1169 ri = c.expand().lcoeff(x);
1173 divide_in_z(pow(ri, delta), pow(psi, delta-1), psi, var+1);
1174 delta = cdeg - ddeg;
1179 /** Return maximum (absolute value) coefficient of a polynomial.
1180 * This function is used internally by heur_gcd().
1182 * @param e expanded multivariate polynomial
1183 * @return maximum coefficient
1185 numeric ex::max_coefficient(void) const
1187 GINAC_ASSERT(bp!=0);
1188 return bp->max_coefficient();
1191 /** Implementation ex::max_coefficient().
1193 numeric basic::max_coefficient(void) const
1198 numeric numeric::max_coefficient(void) const
1203 numeric add::max_coefficient(void) const
1205 epvector::const_iterator it = seq.begin();
1206 epvector::const_iterator itend = seq.end();
1207 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1208 numeric cur_max = abs(ex_to_numeric(overall_coeff));
1209 while (it != itend) {
1211 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
1212 a = abs(ex_to_numeric(it->coeff));
1220 numeric mul::max_coefficient(void) const
1222 #ifdef DO_GINAC_ASSERT
1223 epvector::const_iterator it = seq.begin();
1224 epvector::const_iterator itend = seq.end();
1225 while (it != itend) {
1226 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
1229 #endif // def DO_GINAC_ASSERT
1230 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1231 return abs(ex_to_numeric(overall_coeff));
1235 /** Apply symmetric modular homomorphism to a multivariate polynomial.
1236 * This function is used internally by heur_gcd().
1238 * @param e expanded multivariate polynomial
1240 * @return mapped polynomial
1242 ex ex::smod(const numeric &xi) const
1244 GINAC_ASSERT(bp!=0);
1245 return bp->smod(xi);
1248 ex basic::smod(const numeric &xi) const
1253 ex numeric::smod(const numeric &xi) const
1255 return GiNaC::smod(*this, xi);
1258 ex add::smod(const numeric &xi) const
1261 newseq.reserve(seq.size()+1);
1262 epvector::const_iterator it = seq.begin();
1263 epvector::const_iterator itend = seq.end();
1264 while (it != itend) {
1265 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
1266 numeric coeff = GiNaC::smod(ex_to_numeric(it->coeff), xi);
1267 if (!coeff.is_zero())
1268 newseq.push_back(expair(it->rest, coeff));
1271 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1272 numeric coeff = GiNaC::smod(ex_to_numeric(overall_coeff), xi);
1273 return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
1276 ex mul::smod(const numeric &xi) const
1278 #ifdef DO_GINAC_ASSERT
1279 epvector::const_iterator it = seq.begin();
1280 epvector::const_iterator itend = seq.end();
1281 while (it != itend) {
1282 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
1285 #endif // def DO_GINAC_ASSERT
1286 mul * mulcopyp=new mul(*this);
1287 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1288 mulcopyp->overall_coeff = GiNaC::smod(ex_to_numeric(overall_coeff),xi);
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 /** Compute square-free factorization of multivariate polynomial a(x) using
1695 * YunĀ“s algorithm. Used internally by sqrfree().
1697 * @param a multivariate polynomial over Z[X], treated here as univariate
1699 * @param x variable to factor in
1700 * @return vector of factors sorted in ascending degree */
1701 static exvector sqrfree_yun(const ex &a, const symbol &x)
1707 if (g.is_equal(_ex1())) {
1718 } while (!z.is_zero());
1721 /** Compute square-free factorization of multivariate polynomial in Q[X].
1723 * @param a multivariate polynomial over Q[X]
1724 * @param x lst of variables to factor in, may be left empty for autodetection
1725 * @return polynomail a in square-free factored form. */
1726 ex sqrfree(const ex &a, const lst &l)
1728 if (is_ex_of_type(a,numeric) || // algorithm does not trap a==0
1729 is_ex_of_type(a,symbol)) // shortcut
1731 // If no lst of variables to factorize in was specified we have to
1732 // invent one now. Maybe one can optimize here by reversing the order
1733 // or so, I don't know.
1737 get_symbol_stats(a, _ex0(), sdv);
1738 for (sym_desc_vec::iterator it=sdv.begin(); it!=sdv.end(); ++it)
1739 args.append(*it->sym);
1743 // Find the symbol to factor in at this stage
1744 if (!is_ex_of_type(args.op(0), symbol))
1745 throw (std::runtime_error("sqrfree(): invalid factorization variable"));
1746 const symbol x = ex_to_symbol(args.op(0));
1747 // convert the argument from something in Q[X] to something in Z[X]
1748 numeric lcm = lcm_of_coefficients_denominators(a);
1749 ex tmp = multiply_lcm(a,lcm);
1751 exvector factors = sqrfree_yun(tmp,x);
1752 // construct the next list of symbols with the first element popped
1754 for (int i=1; i<args.nops(); ++i)
1755 newargs.append(args.op(i));
1756 // recurse down the factors in remaining vars
1757 if (newargs.nops()>0) {
1758 for (exvector::iterator i=factors.begin(); i!=factors.end(); ++i)
1759 *i = sqrfree(*i, newargs);
1761 // Done with recursion, now construct the final result
1763 exvector::iterator it = factors.begin();
1764 for (int p = 1; it!=factors.end(); ++it, ++p)
1765 result *= power(*it, p);
1766 // Yun's algorithm does not account for constant factors. (For
1767 // univariate polynomials it works only in the monic case.) We can
1768 // correct this by inserting what has been lost back into the result:
1769 result = result * quo(tmp, result, x);
1770 return result * lcm.inverse();
1775 * Normal form of rational functions
1779 * Note: The internal normal() functions (= basic::normal() and overloaded
1780 * functions) all return lists of the form {numerator, denominator}. This
1781 * is to get around mul::eval()'s automatic expansion of numeric coefficients.
1782 * E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
1783 * the information that (a+b) is the numerator and 3 is the denominator.
1786 /** Create a symbol for replacing the expression "e" (or return a previously
1787 * assigned symbol). The symbol is appended to sym_lst and returned, the
1788 * expression is appended to repl_lst.
1789 * @see ex::normal */
1790 static ex replace_with_symbol(const ex &e, lst &sym_lst, lst &repl_lst)
1792 // Expression already in repl_lst? Then return the assigned symbol
1793 for (unsigned i=0; i<repl_lst.nops(); i++)
1794 if (repl_lst.op(i).is_equal(e))
1795 return sym_lst.op(i);
1797 // Otherwise create new symbol and add to list, taking care that the
1798 // replacement expression doesn't contain symbols from the sym_lst
1799 // because subs() is not recursive
1802 ex e_replaced = e.subs(sym_lst, repl_lst);
1804 repl_lst.append(e_replaced);
1808 /** Create a symbol for replacing the expression "e" (or return a previously
1809 * assigned symbol). An expression of the form "symbol == expression" is added
1810 * to repl_lst and the symbol is returned.
1811 * @see ex::to_rational */
1812 static ex replace_with_symbol(const ex &e, lst &repl_lst)
1814 // Expression already in repl_lst? Then return the assigned symbol
1815 for (unsigned i=0; i<repl_lst.nops(); i++)
1816 if (repl_lst.op(i).op(1).is_equal(e))
1817 return repl_lst.op(i).op(0);
1819 // Otherwise create new symbol and add to list, taking care that the
1820 // replacement expression doesn't contain symbols from the sym_lst
1821 // because subs() is not recursive
1824 ex e_replaced = e.subs(repl_lst);
1825 repl_lst.append(es == e_replaced);
1829 /** Default implementation of ex::normal(). It replaces the object with a
1831 * @see ex::normal */
1832 ex basic::normal(lst &sym_lst, lst &repl_lst, int level) const
1834 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1838 /** Implementation of ex::normal() for symbols. This returns the unmodified symbol.
1839 * @see ex::normal */
1840 ex symbol::normal(lst &sym_lst, lst &repl_lst, int level) const
1842 return (new lst(*this, _ex1()))->setflag(status_flags::dynallocated);
1846 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1847 * into re+I*im and replaces I and non-rational real numbers with a temporary
1849 * @see ex::normal */
1850 ex numeric::normal(lst &sym_lst, lst &repl_lst, int level) const
1852 numeric num = numer();
1855 if (num.is_real()) {
1856 if (!num.is_integer())
1857 numex = replace_with_symbol(numex, sym_lst, repl_lst);
1859 numeric re = num.real(), im = num.imag();
1860 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, sym_lst, repl_lst);
1861 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, sym_lst, repl_lst);
1862 numex = re_ex + im_ex * replace_with_symbol(I, sym_lst, repl_lst);
1865 // Denominator is always a real integer (see numeric::denom())
1866 return (new lst(numex, denom()))->setflag(status_flags::dynallocated);
1870 /** Fraction cancellation.
1871 * @param n numerator
1872 * @param d denominator
1873 * @return cancelled fraction {n, d} as a list */
1874 static ex frac_cancel(const ex &n, const ex &d)
1878 numeric pre_factor = _num1();
1880 //std::clog << "frac_cancel num = " << num << ", den = " << den << endl;
1882 // Handle trivial case where denominator is 1
1883 if (den.is_equal(_ex1()))
1884 return (new lst(num, den))->setflag(status_flags::dynallocated);
1886 // Handle special cases where numerator or denominator is 0
1888 return (new lst(num, _ex1()))->setflag(status_flags::dynallocated);
1889 if (den.expand().is_zero())
1890 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
1892 // Bring numerator and denominator to Z[X] by multiplying with
1893 // LCM of all coefficients' denominators
1894 numeric num_lcm = lcm_of_coefficients_denominators(num);
1895 numeric den_lcm = lcm_of_coefficients_denominators(den);
1896 num = multiply_lcm(num, num_lcm);
1897 den = multiply_lcm(den, den_lcm);
1898 pre_factor = den_lcm / num_lcm;
1900 // Cancel GCD from numerator and denominator
1902 if (gcd(num, den, &cnum, &cden, false) != _ex1()) {
1907 // Make denominator unit normal (i.e. coefficient of first symbol
1908 // as defined by get_first_symbol() is made positive)
1910 if (get_first_symbol(den, x)) {
1911 GINAC_ASSERT(is_ex_exactly_of_type(den.unit(*x),numeric));
1912 if (ex_to_numeric(den.unit(*x)).is_negative()) {
1918 // Return result as list
1919 //std::clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << endl;
1920 return (new lst(num * pre_factor.numer(), den * pre_factor.denom()))->setflag(status_flags::dynallocated);
1924 /** Implementation of ex::normal() for a sum. It expands terms and performs
1925 * fractional addition.
1926 * @see ex::normal */
1927 ex add::normal(lst &sym_lst, lst &repl_lst, int level) const
1930 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1931 else if (level == -max_recursion_level)
1932 throw(std::runtime_error("max recursion level reached"));
1934 // Normalize children and split each one into numerator and denominator
1935 exvector nums, dens;
1936 nums.reserve(seq.size()+1);
1937 dens.reserve(seq.size()+1);
1938 epvector::const_iterator it = seq.begin(), itend = seq.end();
1939 while (it != itend) {
1940 ex n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1);
1941 nums.push_back(n.op(0));
1942 dens.push_back(n.op(1));
1945 ex n = overall_coeff.bp->normal(sym_lst, repl_lst, level-1);
1946 nums.push_back(n.op(0));
1947 dens.push_back(n.op(1));
1948 GINAC_ASSERT(nums.size() == dens.size());
1950 // Now, nums is a vector of all numerators and dens is a vector of
1952 //std::clog << "add::normal uses " << nums.size() << " summands:\n";
1954 // Add fractions sequentially
1955 exvector::const_iterator num_it = nums.begin(), num_itend = nums.end();
1956 exvector::const_iterator den_it = dens.begin(), den_itend = dens.end();
1957 //std::clog << " num = " << *num_it << ", den = " << *den_it << endl;
1958 ex num = *num_it++, den = *den_it++;
1959 while (num_it != num_itend) {
1960 //std::clog << " num = " << *num_it << ", den = " << *den_it << endl;
1961 ex next_num = *num_it++, next_den = *den_it++;
1963 // Trivially add sequences of fractions with identical denominators
1964 while ((den_it != den_itend) && next_den.is_equal(*den_it)) {
1965 next_num += *num_it;
1969 // Additiion of two fractions, taking advantage of the fact that
1970 // the heuristic GCD algorithm computes the cofactors at no extra cost
1971 ex co_den1, co_den2;
1972 ex g = gcd(den, next_den, &co_den1, &co_den2, false);
1973 num = ((num * co_den2) + (next_num * co_den1)).expand();
1974 den *= co_den2; // this is the lcm(den, next_den)
1976 //std::clog << " common denominator = " << den << endl;
1978 // Cancel common factors from num/den
1979 return frac_cancel(num, den);
1983 /** Implementation of ex::normal() for a product. It cancels common factors
1985 * @see ex::normal() */
1986 ex mul::normal(lst &sym_lst, lst &repl_lst, int level) const
1989 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1990 else if (level == -max_recursion_level)
1991 throw(std::runtime_error("max recursion level reached"));
1993 // Normalize children, separate into numerator and denominator
1997 epvector::const_iterator it = seq.begin(), itend = seq.end();
1998 while (it != itend) {
1999 n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1);
2004 n = overall_coeff.bp->normal(sym_lst, repl_lst, level-1);
2008 // Perform fraction cancellation
2009 return frac_cancel(num, den);
2013 /** Implementation of ex::normal() for powers. It normalizes the basis,
2014 * distributes integer exponents to numerator and denominator, and replaces
2015 * non-integer powers by temporary symbols.
2016 * @see ex::normal */
2017 ex power::normal(lst &sym_lst, lst &repl_lst, int level) const
2020 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
2021 else if (level == -max_recursion_level)
2022 throw(std::runtime_error("max recursion level reached"));
2024 // Normalize basis and exponent (exponent gets reassembled)
2025 ex n_basis = basis.bp->normal(sym_lst, repl_lst, level-1);
2026 ex n_exponent = exponent.bp->normal(sym_lst, repl_lst, level-1);
2027 n_exponent = n_exponent.op(0) / n_exponent.op(1);
2029 if (n_exponent.info(info_flags::integer)) {
2031 if (n_exponent.info(info_flags::positive)) {
2033 // (a/b)^n -> {a^n, b^n}
2034 return (new lst(power(n_basis.op(0), n_exponent), power(n_basis.op(1), n_exponent)))->setflag(status_flags::dynallocated);
2036 } else if (n_exponent.info(info_flags::negative)) {
2038 // (a/b)^-n -> {b^n, a^n}
2039 return (new lst(power(n_basis.op(1), -n_exponent), power(n_basis.op(0), -n_exponent)))->setflag(status_flags::dynallocated);
2044 if (n_exponent.info(info_flags::positive)) {
2046 // (a/b)^x -> {sym((a/b)^x), 1}
2047 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);
2049 } else if (n_exponent.info(info_flags::negative)) {
2051 if (n_basis.op(1).is_equal(_ex1())) {
2053 // a^-x -> {1, sym(a^x)}
2054 return (new lst(_ex1(), replace_with_symbol(power(n_basis.op(0), -n_exponent), sym_lst, repl_lst)))->setflag(status_flags::dynallocated);
2058 // (a/b)^-x -> {sym((b/a)^x), 1}
2059 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);
2062 } else { // n_exponent not numeric
2064 // (a/b)^x -> {sym((a/b)^x, 1}
2065 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);
2071 /** Implementation of ex::normal() for pseries. It normalizes each coefficient
2072 * and replaces the series by a temporary symbol.
2073 * @see ex::normal */
2074 ex pseries::normal(lst &sym_lst, lst &repl_lst, int level) const
2077 for (epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i) {
2078 ex restexp = i->rest.normal();
2079 if (!restexp.is_zero())
2080 newseq.push_back(expair(restexp, i->coeff));
2082 ex n = pseries(relational(var,point), newseq);
2083 return (new lst(replace_with_symbol(n, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
2087 /** Implementation of ex::normal() for relationals. It normalizes both sides.
2088 * @see ex::normal */
2089 ex relational::normal(lst &sym_lst, lst &repl_lst, int level) const
2091 return (new lst(relational(lh.normal(), rh.normal(), o), _ex1()))->setflag(status_flags::dynallocated);
2095 /** Normalization of rational functions.
2096 * This function converts an expression to its normal form
2097 * "numerator/denominator", where numerator and denominator are (relatively
2098 * prime) polynomials. Any subexpressions which are not rational functions
2099 * (like non-rational numbers, non-integer powers or functions like sin(),
2100 * cos() etc.) are replaced by temporary symbols which are re-substituted by
2101 * the (normalized) subexpressions before normal() returns (this way, any
2102 * expression can be treated as a rational function). normal() is applied
2103 * recursively to arguments of functions etc.
2105 * @param level maximum depth of recursion
2106 * @return normalized expression */
2107 ex ex::normal(int level) const
2109 lst sym_lst, repl_lst;
2111 ex e = bp->normal(sym_lst, repl_lst, level);
2112 GINAC_ASSERT(is_ex_of_type(e, lst));
2114 // Re-insert replaced symbols
2115 if (sym_lst.nops() > 0)
2116 e = e.subs(sym_lst, repl_lst);
2118 // Convert {numerator, denominator} form back to fraction
2119 return e.op(0) / e.op(1);
2122 /** Numerator of an expression. If the expression is not of the normal form
2123 * "numerator/denominator", it is first converted to this form and then the
2124 * numerator is returned.
2127 * @return numerator */
2128 ex ex::numer(void) const
2130 lst sym_lst, repl_lst;
2132 ex e = bp->normal(sym_lst, repl_lst, 0);
2133 GINAC_ASSERT(is_ex_of_type(e, lst));
2135 // Re-insert replaced symbols
2136 if (sym_lst.nops() > 0)
2137 return e.op(0).subs(sym_lst, repl_lst);
2142 /** Denominator of an expression. If the expression is not of the normal form
2143 * "numerator/denominator", it is first converted to this form and then the
2144 * denominator is returned.
2147 * @return denominator */
2148 ex ex::denom(void) const
2150 lst sym_lst, repl_lst;
2152 ex e = bp->normal(sym_lst, repl_lst, 0);
2153 GINAC_ASSERT(is_ex_of_type(e, lst));
2155 // Re-insert replaced symbols
2156 if (sym_lst.nops() > 0)
2157 return e.op(1).subs(sym_lst, repl_lst);
2163 /** Default implementation of ex::to_rational(). It replaces the object with a
2165 * @see ex::to_rational */
2166 ex basic::to_rational(lst &repl_lst) const
2168 return replace_with_symbol(*this, repl_lst);
2172 /** Implementation of ex::to_rational() for symbols. This returns the
2173 * unmodified symbol.
2174 * @see ex::to_rational */
2175 ex symbol::to_rational(lst &repl_lst) const
2181 /** Implementation of ex::to_rational() for a numeric. It splits complex
2182 * numbers into re+I*im and replaces I and non-rational real numbers with a
2184 * @see ex::to_rational */
2185 ex numeric::to_rational(lst &repl_lst) const
2189 return replace_with_symbol(*this, repl_lst);
2191 numeric re = real();
2192 numeric im = imag();
2193 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl_lst);
2194 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl_lst);
2195 return re_ex + im_ex * replace_with_symbol(I, repl_lst);
2201 /** Implementation of ex::to_rational() for powers. It replaces non-integer
2202 * powers by temporary symbols.
2203 * @see ex::to_rational */
2204 ex power::to_rational(lst &repl_lst) const
2206 if (exponent.info(info_flags::integer))
2207 return power(basis.to_rational(repl_lst), exponent);
2209 return replace_with_symbol(*this, repl_lst);
2213 /** Implementation of ex::to_rational() for expairseqs.
2214 * @see ex::to_rational */
2215 ex expairseq::to_rational(lst &repl_lst) const
2218 s.reserve(seq.size());
2219 for (epvector::const_iterator it=seq.begin(); it!=seq.end(); ++it) {
2220 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*it).to_rational(repl_lst)));
2221 // s.push_back(combine_ex_with_coeff_to_pair((*it).rest.to_rational(repl_lst),
2223 ex oc = overall_coeff.to_rational(repl_lst);
2224 if (oc.info(info_flags::numeric))
2225 return thisexpairseq(s, overall_coeff);
2226 else s.push_back(combine_ex_with_coeff_to_pair(oc,_ex1()));
2227 return thisexpairseq(s, default_overall_coeff());
2231 /** Rationalization of non-rational functions.
2232 * This function converts a general expression to a rational polynomial
2233 * by replacing all non-rational subexpressions (like non-rational numbers,
2234 * non-integer powers or functions like sin(), cos() etc.) to temporary
2235 * symbols. This makes it possible to use functions like gcd() and divide()
2236 * on non-rational functions by applying to_rational() on the arguments,
2237 * calling the desired function and re-substituting the temporary symbols
2238 * in the result. To make the last step possible, all temporary symbols and
2239 * their associated expressions are collected in the list specified by the
2240 * repl_lst parameter in the form {symbol == expression}, ready to be passed
2241 * as an argument to ex::subs().
2243 * @param repl_lst collects a list of all temporary symbols and their replacements
2244 * @return rationalized expression */
2245 ex ex::to_rational(lst &repl_lst) const
2247 return bp->to_rational(repl_lst);
2251 } // namespace GiNaC