3 * This file implements several functions that work on univariate and
4 * multivariate polynomials and rational functions.
5 * These functions include polynomial quotient and remainder, GCD and LCM
6 * computation, square-free factorization and rational function normalization. */
9 * GiNaC Copyright (C) 1999-2000 Johannes Gutenberg University Mainz, Germany
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
35 #include "expairseq.h"
44 #include "relational.h"
49 #ifndef NO_NAMESPACE_GINAC
51 #endif // ndef NO_NAMESPACE_GINAC
53 // If comparing expressions (ex::compare()) is fast, you can set this to 1.
54 // Some routines like quo(), rem() and gcd() will then return a quick answer
55 // when they are called with two identical arguments.
56 #define FAST_COMPARE 1
58 // Set this if you want divide_in_z() to use remembering
59 #define USE_REMEMBER 0
61 // Set this if you want divide_in_z() to use trial division followed by
62 // polynomial interpolation (always slower except for completely dense
64 #define USE_TRIAL_DIVISION 0
66 // Set this to enable some statistical output for the GCD routines
71 // Statistics variables
72 static int gcd_called = 0;
73 static int sr_gcd_called = 0;
74 static int heur_gcd_called = 0;
75 static int heur_gcd_failed = 0;
77 // Print statistics at end of program
78 static struct _stat_print {
81 cout << "gcd() called " << gcd_called << " times\n";
82 cout << "sr_gcd() called " << sr_gcd_called << " times\n";
83 cout << "heur_gcd() called " << heur_gcd_called << " times\n";
84 cout << "heur_gcd() failed " << heur_gcd_failed << " times\n";
90 /** Return pointer to first symbol found in expression. Due to GiNaCĀ“s
91 * internal ordering of terms, it may not be obvious which symbol this
92 * function returns for a given expression.
94 * @param e expression to search
95 * @param x pointer to first symbol found (returned)
96 * @return "false" if no symbol was found, "true" otherwise */
97 static bool get_first_symbol(const ex &e, const symbol *&x)
99 if (is_ex_exactly_of_type(e, symbol)) {
100 x = static_cast<symbol *>(e.bp);
102 } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
103 for (unsigned i=0; i<e.nops(); i++)
104 if (get_first_symbol(e.op(i), x))
106 } else if (is_ex_exactly_of_type(e, power)) {
107 if (get_first_symbol(e.op(0), x))
115 * Statistical information about symbols in polynomials
118 /** This structure holds information about the highest and lowest degrees
119 * in which a symbol appears in two multivariate polynomials "a" and "b".
120 * A vector of these structures with information about all symbols in
121 * two polynomials can be created with the function get_symbol_stats().
123 * @see get_symbol_stats */
125 /** Pointer to symbol */
128 /** Highest degree of symbol in polynomial "a" */
131 /** Highest degree of symbol in polynomial "b" */
134 /** Lowest degree of symbol in polynomial "a" */
137 /** Lowest degree of symbol in polynomial "b" */
140 /** Maximum of deg_a and deg_b (Used for sorting) */
143 /** Commparison operator for sorting */
144 bool operator<(const sym_desc &x) const {return max_deg < x.max_deg;}
147 // Vector of sym_desc structures
148 typedef vector<sym_desc> sym_desc_vec;
150 // Add symbol the sym_desc_vec (used internally by get_symbol_stats())
151 static void add_symbol(const symbol *s, sym_desc_vec &v)
153 sym_desc_vec::iterator it = v.begin(), itend = v.end();
154 while (it != itend) {
155 if (it->sym->compare(*s) == 0) // If it's already in there, don't add it a second time
164 // Collect all symbols of an expression (used internally by get_symbol_stats())
165 static void collect_symbols(const ex &e, sym_desc_vec &v)
167 if (is_ex_exactly_of_type(e, symbol)) {
168 add_symbol(static_cast<symbol *>(e.bp), v);
169 } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
170 for (unsigned i=0; i<e.nops(); i++)
171 collect_symbols(e.op(i), v);
172 } else if (is_ex_exactly_of_type(e, power)) {
173 collect_symbols(e.op(0), v);
177 /** Collect statistical information about symbols in polynomials.
178 * This function fills in a vector of "sym_desc" structs which contain
179 * information about the highest and lowest degrees of all symbols that
180 * appear in two polynomials. The vector is then sorted by minimum
181 * degree (lowest to highest). The information gathered by this
182 * function is used by the GCD routines to identify trivial factors
183 * and to determine which variable to choose as the main variable
184 * for GCD computation.
186 * @param a first multivariate polynomial
187 * @param b second multivariate polynomial
188 * @param v vector of sym_desc structs (filled in) */
189 static void get_symbol_stats(const ex &a, const ex &b, sym_desc_vec &v)
191 collect_symbols(a.eval(), v); // eval() to expand assigned symbols
192 collect_symbols(b.eval(), v);
193 sym_desc_vec::iterator it = v.begin(), itend = v.end();
194 while (it != itend) {
195 int deg_a = a.degree(*(it->sym));
196 int deg_b = b.degree(*(it->sym));
199 it->max_deg = max(deg_a, deg_b);
200 it->ldeg_a = a.ldegree(*(it->sym));
201 it->ldeg_b = b.ldegree(*(it->sym));
204 sort(v.begin(), v.end());
206 clog << "Symbols:\n";
207 it = v.begin(); itend = v.end();
208 while (it != itend) {
209 clog << " " << *it->sym << ": deg_a=" << it->deg_a << ", deg_b=" << it->deg_b << ", ldeg_a=" << it->ldeg_a << ", ldeg_b=" << it->ldeg_b << ", max_deg=" << it->max_deg << endl;
210 clog << " lcoeff_a=" << a.lcoeff(*(it->sym)) << ", lcoeff_b=" << b.lcoeff(*(it->sym)) << endl;
218 * Computation of LCM of denominators of coefficients of a polynomial
221 // Compute LCM of denominators of coefficients by going through the
222 // expression recursively (used internally by lcm_of_coefficients_denominators())
223 static numeric lcmcoeff(const ex &e, const numeric &l)
225 if (e.info(info_flags::rational))
226 return lcm(ex_to_numeric(e).denom(), l);
227 else if (is_ex_exactly_of_type(e, add)) {
229 for (unsigned i=0; i<e.nops(); i++)
230 c = lcmcoeff(e.op(i), c);
232 } else if (is_ex_exactly_of_type(e, mul)) {
234 for (unsigned i=0; i<e.nops(); i++)
235 c *= lcmcoeff(e.op(i), _num1());
237 } else if (is_ex_exactly_of_type(e, power))
238 return pow(lcmcoeff(e.op(0), l), ex_to_numeric(e.op(1)));
242 /** Compute LCM of denominators of coefficients of a polynomial.
243 * Given a polynomial with rational coefficients, this function computes
244 * the LCM of the denominators of all coefficients. This can be used
245 * to bring a polynomial from Q[X] to Z[X].
247 * @param e multivariate polynomial (need not be expanded)
248 * @return LCM of denominators of coefficients */
249 static numeric lcm_of_coefficients_denominators(const ex &e)
251 return lcmcoeff(e, _num1());
254 /** Bring polynomial from Q[X] to Z[X] by multiplying in the previously
255 * determined LCM of the coefficient's denominators.
257 * @param e multivariate polynomial (need not be expanded)
258 * @param lcm LCM to multiply in */
259 static ex multiply_lcm(const ex &e, const numeric &lcm)
261 if (is_ex_exactly_of_type(e, mul)) {
263 numeric lcm_accum = _num1();
264 for (unsigned i=0; i<e.nops(); i++) {
265 numeric op_lcm = lcmcoeff(e.op(i), _num1());
266 c *= multiply_lcm(e.op(i), op_lcm);
269 c *= lcm / lcm_accum;
271 } else if (is_ex_exactly_of_type(e, add)) {
273 for (unsigned i=0; i<e.nops(); i++)
274 c += multiply_lcm(e.op(i), lcm);
276 } else if (is_ex_exactly_of_type(e, power)) {
277 return pow(multiply_lcm(e.op(0), lcm.power(ex_to_numeric(e.op(1)).inverse())), e.op(1));
283 /** Compute the integer content (= GCD of all numeric coefficients) of an
284 * expanded polynomial.
286 * @param e expanded polynomial
287 * @return integer content */
288 numeric ex::integer_content(void) const
291 return bp->integer_content();
294 numeric basic::integer_content(void) const
299 numeric numeric::integer_content(void) const
304 numeric add::integer_content(void) const
306 epvector::const_iterator it = seq.begin();
307 epvector::const_iterator itend = seq.end();
309 while (it != itend) {
310 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
311 GINAC_ASSERT(is_ex_exactly_of_type(it->coeff,numeric));
312 c = gcd(ex_to_numeric(it->coeff), c);
315 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
316 c = gcd(ex_to_numeric(overall_coeff),c);
320 numeric mul::integer_content(void) const
322 #ifdef DO_GINAC_ASSERT
323 epvector::const_iterator it = seq.begin();
324 epvector::const_iterator itend = seq.end();
325 while (it != itend) {
326 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
329 #endif // def DO_GINAC_ASSERT
330 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
331 return abs(ex_to_numeric(overall_coeff));
336 * Polynomial quotients and remainders
339 /** Quotient q(x) of polynomials a(x) and b(x) in Q[x].
340 * It satisfies a(x)=b(x)*q(x)+r(x).
342 * @param a first polynomial in x (dividend)
343 * @param b second polynomial in x (divisor)
344 * @param x a and b are polynomials in x
345 * @param check_args check whether a and b are polynomials with rational
346 * coefficients (defaults to "true")
347 * @return quotient of a and b in Q[x] */
348 ex quo(const ex &a, const ex &b, const symbol &x, bool check_args)
351 throw(std::overflow_error("quo: division by zero"));
352 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
358 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
359 throw(std::invalid_argument("quo: arguments must be polynomials over the rationals"));
361 // Polynomial long division
366 int bdeg = b.degree(x);
367 int rdeg = r.degree(x);
368 ex blcoeff = b.expand().coeff(x, bdeg);
369 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
370 while (rdeg >= bdeg) {
371 ex term, rcoeff = r.coeff(x, rdeg);
372 if (blcoeff_is_numeric)
373 term = rcoeff / blcoeff;
375 if (!divide(rcoeff, blcoeff, term, false))
376 return *new ex(fail());
378 term *= power(x, rdeg - bdeg);
380 r -= (term * b).expand();
389 /** Remainder r(x) of polynomials a(x) and b(x) in Q[x].
390 * It satisfies a(x)=b(x)*q(x)+r(x).
392 * @param a first polynomial in x (dividend)
393 * @param b second polynomial in x (divisor)
394 * @param x a and b are polynomials in x
395 * @param check_args check whether a and b are polynomials with rational
396 * coefficients (defaults to "true")
397 * @return remainder of a(x) and b(x) in Q[x] */
398 ex rem(const ex &a, const ex &b, const symbol &x, bool check_args)
401 throw(std::overflow_error("rem: division by zero"));
402 if (is_ex_exactly_of_type(a, numeric)) {
403 if (is_ex_exactly_of_type(b, numeric))
412 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
413 throw(std::invalid_argument("rem: arguments must be polynomials over the rationals"));
415 // Polynomial long division
419 int bdeg = b.degree(x);
420 int rdeg = r.degree(x);
421 ex blcoeff = b.expand().coeff(x, bdeg);
422 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
423 while (rdeg >= bdeg) {
424 ex term, rcoeff = r.coeff(x, rdeg);
425 if (blcoeff_is_numeric)
426 term = rcoeff / blcoeff;
428 if (!divide(rcoeff, blcoeff, term, false))
429 return *new ex(fail());
431 term *= power(x, rdeg - bdeg);
432 r -= (term * b).expand();
441 /** Pseudo-remainder of polynomials a(x) and b(x) in Z[x].
443 * @param a first polynomial in x (dividend)
444 * @param b second polynomial in x (divisor)
445 * @param x a and b are polynomials in x
446 * @param check_args check whether a and b are polynomials with rational
447 * coefficients (defaults to "true")
448 * @return pseudo-remainder of a(x) and b(x) in Z[x] */
449 ex prem(const ex &a, const ex &b, const symbol &x, bool check_args)
452 throw(std::overflow_error("prem: division by zero"));
453 if (is_ex_exactly_of_type(a, numeric)) {
454 if (is_ex_exactly_of_type(b, numeric))
459 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
460 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
462 // Polynomial long division
465 int rdeg = r.degree(x);
466 int bdeg = eb.degree(x);
469 blcoeff = eb.coeff(x, bdeg);
473 eb -= blcoeff * power(x, bdeg);
477 int delta = rdeg - bdeg + 1, i = 0;
478 while (rdeg >= bdeg && !r.is_zero()) {
479 ex rlcoeff = r.coeff(x, rdeg);
480 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
484 r -= rlcoeff * power(x, rdeg);
485 r = (blcoeff * r).expand() - term;
489 return power(blcoeff, delta - i) * r;
493 /** Sparse pseudo-remainder of polynomials a(x) and b(x) in Z[x].
495 * @param a first polynomial in x (dividend)
496 * @param b second polynomial in x (divisor)
497 * @param x a and b are polynomials in x
498 * @param check_args check whether a and b are polynomials with rational
499 * coefficients (defaults to "true")
500 * @return sparse pseudo-remainder of a(x) and b(x) in Z[x] */
502 ex sprem(const ex &a, const ex &b, const symbol &x, bool check_args)
505 throw(std::overflow_error("prem: division by zero"));
506 if (is_ex_exactly_of_type(a, numeric)) {
507 if (is_ex_exactly_of_type(b, numeric))
512 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
513 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
515 // Polynomial long division
518 int rdeg = r.degree(x);
519 int bdeg = eb.degree(x);
522 blcoeff = eb.coeff(x, bdeg);
526 eb -= blcoeff * power(x, bdeg);
530 while (rdeg >= bdeg && !r.is_zero()) {
531 ex rlcoeff = r.coeff(x, rdeg);
532 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
536 r -= rlcoeff * power(x, rdeg);
537 r = (blcoeff * r).expand() - term;
544 /** Exact polynomial division of a(X) by b(X) in Q[X].
546 * @param a first multivariate polynomial (dividend)
547 * @param b second multivariate polynomial (divisor)
548 * @param q quotient (returned)
549 * @param check_args check whether a and b are polynomials with rational
550 * coefficients (defaults to "true")
551 * @return "true" when exact division succeeds (quotient returned in q),
552 * "false" otherwise */
553 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
557 throw(std::overflow_error("divide: division by zero"));
560 if (is_ex_exactly_of_type(b, numeric)) {
563 } else if (is_ex_exactly_of_type(a, numeric))
571 if (check_args && (!a.info(info_flags::rational_polynomial) ||
572 !b.info(info_flags::rational_polynomial)))
573 throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
577 if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
578 throw(std::invalid_argument("invalid expression in divide()"));
580 // Polynomial long division (recursive)
584 int bdeg = b.degree(*x);
585 int rdeg = r.degree(*x);
586 ex blcoeff = b.expand().coeff(*x, bdeg);
587 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
588 while (rdeg >= bdeg) {
589 ex term, rcoeff = r.coeff(*x, rdeg);
590 if (blcoeff_is_numeric)
591 term = rcoeff / blcoeff;
593 if (!divide(rcoeff, blcoeff, term, false))
595 term *= power(*x, rdeg - bdeg);
597 r -= (term * b).expand();
611 typedef pair<ex, ex> ex2;
612 typedef pair<ex, bool> exbool;
615 bool operator() (const ex2 p, const ex2 q) const
617 return p.first.compare(q.first) < 0 || (!(q.first.compare(p.first) < 0) && p.second.compare(q.second) < 0);
621 typedef map<ex2, exbool, ex2_less> ex2_exbool_remember;
625 /** Exact polynomial division of a(X) by b(X) in Z[X].
626 * This functions works like divide() but the input and output polynomials are
627 * in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
628 * divide(), it doesnĀ“t check whether the input polynomials really are integer
629 * polynomials, so be careful of what you pass in. Also, you have to run
630 * get_symbol_stats() over the input polynomials before calling this function
631 * and pass an iterator to the first element of the sym_desc vector. This
632 * function is used internally by the heur_gcd().
634 * @param a first multivariate polynomial (dividend)
635 * @param b second multivariate polynomial (divisor)
636 * @param q quotient (returned)
637 * @param var iterator to first element of vector of sym_desc structs
638 * @return "true" when exact division succeeds (the quotient is returned in
639 * q), "false" otherwise.
640 * @see get_symbol_stats, heur_gcd */
641 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
645 throw(std::overflow_error("divide_in_z: division by zero"));
646 if (b.is_equal(_ex1())) {
650 if (is_ex_exactly_of_type(a, numeric)) {
651 if (is_ex_exactly_of_type(b, numeric)) {
653 return q.info(info_flags::integer);
666 static ex2_exbool_remember dr_remember;
667 ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
668 if (remembered != dr_remember.end()) {
669 q = remembered->second.first;
670 return remembered->second.second;
675 const symbol *x = var->sym;
678 int adeg = a.degree(*x), bdeg = b.degree(*x);
682 #if USE_TRIAL_DIVISION
684 // Trial division with polynomial interpolation
687 // Compute values at evaluation points 0..adeg
688 vector<numeric> alpha; alpha.reserve(adeg + 1);
689 exvector u; u.reserve(adeg + 1);
690 numeric point = _num0();
692 for (i=0; i<=adeg; i++) {
693 ex bs = b.subs(*x == point);
694 while (bs.is_zero()) {
696 bs = b.subs(*x == point);
698 if (!divide_in_z(a.subs(*x == point), bs, c, var+1))
700 alpha.push_back(point);
706 vector<numeric> rcp; rcp.reserve(adeg + 1);
707 rcp.push_back(_num0());
708 for (k=1; k<=adeg; k++) {
709 numeric product = alpha[k] - alpha[0];
711 product *= alpha[k] - alpha[i];
712 rcp.push_back(product.inverse());
715 // Compute Newton coefficients
716 exvector v; v.reserve(adeg + 1);
718 for (k=1; k<=adeg; k++) {
720 for (i=k-2; i>=0; i--)
721 temp = temp * (alpha[k] - alpha[i]) + v[i];
722 v.push_back((u[k] - temp) * rcp[k]);
725 // Convert from Newton form to standard form
727 for (k=adeg-1; k>=0; k--)
728 c = c * (*x - alpha[k]) + v[k];
730 if (c.degree(*x) == (adeg - bdeg)) {
738 // Polynomial long division (recursive)
744 ex blcoeff = eb.coeff(*x, bdeg);
745 while (rdeg >= bdeg) {
746 ex term, rcoeff = r.coeff(*x, rdeg);
747 if (!divide_in_z(rcoeff, blcoeff, term, var+1))
749 term = (term * power(*x, rdeg - bdeg)).expand();
751 r -= (term * eb).expand();
754 dr_remember[ex2(a, b)] = exbool(q, true);
761 dr_remember[ex2(a, b)] = exbool(q, false);
770 * Separation of unit part, content part and primitive part of polynomials
773 /** Compute unit part (= sign of leading coefficient) of a multivariate
774 * polynomial in Z[x]. The product of unit part, content part, and primitive
775 * part is the polynomial itself.
777 * @param x variable in which to compute the unit part
779 * @see ex::content, ex::primpart */
780 ex ex::unit(const symbol &x) const
782 ex c = expand().lcoeff(x);
783 if (is_ex_exactly_of_type(c, numeric))
784 return c < _ex0() ? _ex_1() : _ex1();
787 if (get_first_symbol(c, y))
790 throw(std::invalid_argument("invalid expression in unit()"));
795 /** Compute content part (= unit normal GCD of all coefficients) of a
796 * multivariate polynomial in Z[x]. The product of unit part, content part,
797 * and primitive part is the polynomial itself.
799 * @param x variable in which to compute the content part
800 * @return content part
801 * @see ex::unit, ex::primpart */
802 ex ex::content(const symbol &x) const
806 if (is_ex_exactly_of_type(*this, numeric))
807 return info(info_flags::negative) ? -*this : *this;
812 // First, try the integer content
813 ex c = e.integer_content();
815 ex lcoeff = r.lcoeff(x);
816 if (lcoeff.info(info_flags::integer))
819 // GCD of all coefficients
820 int deg = e.degree(x);
821 int ldeg = e.ldegree(x);
823 return e.lcoeff(x) / e.unit(x);
825 for (int i=ldeg; i<=deg; i++)
826 c = gcd(e.coeff(x, i), c, NULL, NULL, false);
831 /** Compute primitive part of a multivariate polynomial in Z[x].
832 * The product of unit part, content part, and primitive part is the
835 * @param x variable in which to compute the primitive part
836 * @return primitive part
837 * @see ex::unit, ex::content */
838 ex ex::primpart(const symbol &x) const
842 if (is_ex_exactly_of_type(*this, numeric))
849 if (is_ex_exactly_of_type(c, numeric))
850 return *this / (c * u);
852 return quo(*this, c * u, x, false);
856 /** Compute primitive part of a multivariate polynomial in Z[x] when the
857 * content part is already known. This function is faster in computing the
858 * primitive part than the previous function.
860 * @param x variable in which to compute the primitive part
861 * @param c previously computed content part
862 * @return primitive part */
863 ex ex::primpart(const symbol &x, const ex &c) const
869 if (is_ex_exactly_of_type(*this, numeric))
873 if (is_ex_exactly_of_type(c, numeric))
874 return *this / (c * u);
876 return quo(*this, c * u, x, false);
881 * GCD of multivariate polynomials
884 /** Compute GCD of polynomials in Q[X] using the Euclidean algorithm (not
885 * really suited for multivariate GCDs). This function is only provided for
888 * @param a first multivariate polynomial
889 * @param b second multivariate polynomial
890 * @param x pointer to symbol (main variable) in which to compute the GCD in
891 * @return the GCD as a new expression
894 static ex eu_gcd(const ex &a, const ex &b, const symbol *x)
896 //clog << "eu_gcd(" << a << "," << b << ")\n";
898 // Sort c and d so that c has higher degree
900 int adeg = a.degree(*x), bdeg = b.degree(*x);
910 c = c / c.lcoeff(*x);
911 d = d / d.lcoeff(*x);
913 // Euclidean algorithm
916 //clog << " d = " << d << endl;
917 r = rem(c, d, *x, false);
919 return d / d.lcoeff(*x);
926 /** Compute GCD of multivariate polynomials using the Euclidean PRS algorithm
927 * with pseudo-remainders ("World's Worst GCD Algorithm", staying in Z[X]).
928 * This function is only provided for testing purposes.
930 * @param a first multivariate polynomial
931 * @param b second multivariate polynomial
932 * @param x pointer to symbol (main variable) in which to compute the GCD in
933 * @return the GCD as a new expression
936 static ex euprem_gcd(const ex &a, const ex &b, const symbol *x)
938 //clog << "euprem_gcd(" << a << "," << b << ")\n";
940 // Sort c and d so that c has higher degree
942 int adeg = a.degree(*x), bdeg = b.degree(*x);
951 // Calculate GCD of contents
952 ex gamma = gcd(c.content(*x), d.content(*x), NULL, NULL, false);
954 // Euclidean algorithm with pseudo-remainders
957 //clog << " d = " << d << endl;
958 r = prem(c, d, *x, false);
960 return d.primpart(*x) * gamma;
967 /** Compute GCD of multivariate polynomials using the primitive Euclidean
968 * PRS algorithm (complete content removal at each step). This function is
969 * only provided for testing purposes.
971 * @param a first multivariate polynomial
972 * @param b second multivariate polynomial
973 * @param x pointer to symbol (main variable) in which to compute the GCD in
974 * @return the GCD as a new expression
977 static ex peu_gcd(const ex &a, const ex &b, const symbol *x)
979 //clog << "peu_gcd(" << a << "," << b << ")\n";
981 // Sort c and d so that c has higher degree
983 int adeg = a.degree(*x), bdeg = b.degree(*x);
995 // Remove content from c and d, to be attached to GCD later
996 ex cont_c = c.content(*x);
997 ex cont_d = d.content(*x);
998 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1001 c = c.primpart(*x, cont_c);
1002 d = d.primpart(*x, cont_d);
1004 // Euclidean algorithm with content removal
1007 //clog << " d = " << d << endl;
1008 r = prem(c, d, *x, false);
1017 /** Compute GCD of multivariate polynomials using the reduced PRS algorithm.
1018 * This function is only provided for testing purposes.
1020 * @param a first multivariate polynomial
1021 * @param b second multivariate polynomial
1022 * @param x pointer to symbol (main variable) in which to compute the GCD in
1023 * @return the GCD as a new expression
1026 static ex red_gcd(const ex &a, const ex &b, const symbol *x)
1028 //clog << "red_gcd(" << a << "," << b << ")\n";
1030 // Sort c and d so that c has higher degree
1032 int adeg = a.degree(*x), bdeg = b.degree(*x);
1046 // Remove content from c and d, to be attached to GCD later
1047 ex cont_c = c.content(*x);
1048 ex cont_d = d.content(*x);
1049 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1052 c = c.primpart(*x, cont_c);
1053 d = d.primpart(*x, cont_d);
1055 // First element of divisor sequence
1057 int delta = cdeg - ddeg;
1060 // Calculate polynomial pseudo-remainder
1061 //clog << " d = " << d << endl;
1062 r = prem(c, d, *x, false);
1064 return gamma * d.primpart(*x);
1068 if (!divide(r, pow(ri, delta), d, false))
1069 throw(std::runtime_error("invalid expression in red_gcd(), division failed"));
1070 ddeg = d.degree(*x);
1072 if (is_ex_exactly_of_type(r, numeric))
1075 return gamma * r.primpart(*x);
1078 ri = c.expand().lcoeff(*x);
1079 delta = cdeg - ddeg;
1084 /** Compute GCD of multivariate polynomials using the subresultant PRS
1085 * algorithm. This function is used internally by gcd().
1087 * @param a first multivariate polynomial
1088 * @param b second multivariate polynomial
1089 * @param var iterator to first element of vector of sym_desc structs
1090 * @return the GCD as a new expression
1093 static ex sr_gcd(const ex &a, const ex &b, sym_desc_vec::const_iterator var)
1095 //clog << "sr_gcd(" << a << "," << b << ")\n";
1100 // The first symbol is our main variable
1101 const symbol &x = *(var->sym);
1103 // Sort c and d so that c has higher degree
1105 int adeg = a.degree(x), bdeg = b.degree(x);
1119 // Remove content from c and d, to be attached to GCD later
1120 ex cont_c = c.content(x);
1121 ex cont_d = d.content(x);
1122 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1125 c = c.primpart(x, cont_c);
1126 d = d.primpart(x, cont_d);
1127 //clog << " content " << gamma << " removed, continuing with sr_gcd(" << c << "," << d << ")\n";
1129 // First element of subresultant sequence
1130 ex r = _ex0(), ri = _ex1(), psi = _ex1();
1131 int delta = cdeg - ddeg;
1134 // Calculate polynomial pseudo-remainder
1135 //clog << " start of loop, psi = " << psi << ", calculating pseudo-remainder...\n";
1136 //clog << " d = " << d << endl;
1137 r = prem(c, d, x, false);
1139 return gamma * d.primpart(x);
1142 //clog << " dividing...\n";
1143 if (!divide_in_z(r, ri * pow(psi, delta), d, var+1))
1144 throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
1147 if (is_ex_exactly_of_type(r, numeric))
1150 return gamma * r.primpart(x);
1153 // Next element of subresultant sequence
1154 //clog << " calculating next subresultant...\n";
1155 ri = c.expand().lcoeff(x);
1159 divide_in_z(pow(ri, delta), pow(psi, delta-1), psi, var+1);
1160 delta = cdeg - ddeg;
1165 /** Return maximum (absolute value) coefficient of a polynomial.
1166 * This function is used internally by heur_gcd().
1168 * @param e expanded multivariate polynomial
1169 * @return maximum coefficient
1171 numeric ex::max_coefficient(void) const
1173 GINAC_ASSERT(bp!=0);
1174 return bp->max_coefficient();
1177 numeric basic::max_coefficient(void) const
1182 numeric numeric::max_coefficient(void) const
1187 numeric add::max_coefficient(void) const
1189 epvector::const_iterator it = seq.begin();
1190 epvector::const_iterator itend = seq.end();
1191 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1192 numeric cur_max = abs(ex_to_numeric(overall_coeff));
1193 while (it != itend) {
1195 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
1196 a = abs(ex_to_numeric(it->coeff));
1204 numeric mul::max_coefficient(void) const
1206 #ifdef DO_GINAC_ASSERT
1207 epvector::const_iterator it = seq.begin();
1208 epvector::const_iterator itend = seq.end();
1209 while (it != itend) {
1210 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
1213 #endif // def DO_GINAC_ASSERT
1214 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1215 return abs(ex_to_numeric(overall_coeff));
1219 /** Apply symmetric modular homomorphism to a multivariate polynomial.
1220 * This function is used internally by heur_gcd().
1222 * @param e expanded multivariate polynomial
1224 * @return mapped polynomial
1226 ex ex::smod(const numeric &xi) const
1228 GINAC_ASSERT(bp!=0);
1229 return bp->smod(xi);
1232 ex basic::smod(const numeric &xi) const
1237 ex numeric::smod(const numeric &xi) const
1239 #ifndef NO_NAMESPACE_GINAC
1240 return GiNaC::smod(*this, xi);
1241 #else // ndef NO_NAMESPACE_GINAC
1242 return ::smod(*this, xi);
1243 #endif // ndef NO_NAMESPACE_GINAC
1246 ex add::smod(const numeric &xi) const
1249 newseq.reserve(seq.size()+1);
1250 epvector::const_iterator it = seq.begin();
1251 epvector::const_iterator itend = seq.end();
1252 while (it != itend) {
1253 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
1254 #ifndef NO_NAMESPACE_GINAC
1255 numeric coeff = GiNaC::smod(ex_to_numeric(it->coeff), xi);
1256 #else // ndef NO_NAMESPACE_GINAC
1257 numeric coeff = ::smod(ex_to_numeric(it->coeff), xi);
1258 #endif // ndef NO_NAMESPACE_GINAC
1259 if (!coeff.is_zero())
1260 newseq.push_back(expair(it->rest, coeff));
1263 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1264 #ifndef NO_NAMESPACE_GINAC
1265 numeric coeff = GiNaC::smod(ex_to_numeric(overall_coeff), xi);
1266 #else // ndef NO_NAMESPACE_GINAC
1267 numeric coeff = ::smod(ex_to_numeric(overall_coeff), xi);
1268 #endif // ndef NO_NAMESPACE_GINAC
1269 return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
1272 ex mul::smod(const numeric &xi) const
1274 #ifdef DO_GINAC_ASSERT
1275 epvector::const_iterator it = seq.begin();
1276 epvector::const_iterator itend = seq.end();
1277 while (it != itend) {
1278 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
1281 #endif // def DO_GINAC_ASSERT
1282 mul * mulcopyp=new mul(*this);
1283 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1284 #ifndef NO_NAMESPACE_GINAC
1285 mulcopyp->overall_coeff = GiNaC::smod(ex_to_numeric(overall_coeff),xi);
1286 #else // ndef NO_NAMESPACE_GINAC
1287 mulcopyp->overall_coeff = ::smod(ex_to_numeric(overall_coeff),xi);
1288 #endif // ndef NO_NAMESPACE_GINAC
1289 mulcopyp->clearflag(status_flags::evaluated);
1290 mulcopyp->clearflag(status_flags::hash_calculated);
1291 return mulcopyp->setflag(status_flags::dynallocated);
1295 /** xi-adic polynomial interpolation */
1296 static ex interpolate(const ex &gamma, const numeric &xi, const symbol &x)
1300 numeric rxi = xi.inverse();
1301 for (int i=0; !e.is_zero(); i++) {
1303 g += gi * power(x, i);
1309 /** Exception thrown by heur_gcd() to signal failure. */
1310 class gcdheu_failed {};
1312 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1313 * get_symbol_stats() must have been called previously with the input
1314 * polynomials and an iterator to the first element of the sym_desc vector
1315 * passed in. This function is used internally by gcd().
1317 * @param a first multivariate polynomial (expanded)
1318 * @param b second multivariate polynomial (expanded)
1319 * @param ca cofactor of polynomial a (returned), NULL to suppress
1320 * calculation of cofactor
1321 * @param cb cofactor of polynomial b (returned), NULL to suppress
1322 * calculation of cofactor
1323 * @param var iterator to first element of vector of sym_desc structs
1324 * @return the GCD as a new expression
1326 * @exception gcdheu_failed() */
1327 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
1329 //clog << "heur_gcd(" << a << "," << b << ")\n";
1334 // GCD of two numeric values -> CLN
1335 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1336 numeric g = gcd(ex_to_numeric(a), ex_to_numeric(b));
1341 *ca = ex_to_numeric(a).mul(rg);
1343 *cb = ex_to_numeric(b).mul(rg);
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 = max(p.degree(x), q.degree(x));
1357 // Find evaluation point
1358 numeric mp = p.max_coefficient(), mq = q.max_coefficient();
1361 xi = mq * _num2() + _num2();
1363 xi = mp * _num2() + _num2();
1366 for (int t=0; t<6; t++) {
1367 if (xi.int_length() * maxdeg > 100000) {
1368 //clog << "giving up heur_gcd, xi.int_length = " << xi.int_length() << ", maxdeg = " << maxdeg << endl;
1369 throw gcdheu_failed();
1372 // Apply evaluation homomorphism and calculate GCD
1374 ex gamma = heur_gcd(p.subs(x == xi), q.subs(x == xi), &cp, &cq, var+1).expand();
1375 if (!is_ex_exactly_of_type(gamma, fail)) {
1377 // Reconstruct polynomial from GCD of mapped polynomials
1378 ex g = interpolate(gamma, xi, x);
1380 // Remove integer content
1381 g /= g.integer_content();
1383 // If the calculated polynomial divides both p and q, this is the GCD
1385 if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1387 ex lc = g.lcoeff(x);
1388 if (is_ex_exactly_of_type(lc, numeric) && ex_to_numeric(lc).is_negative())
1394 cp = interpolate(cp, xi, x);
1395 if (divide_in_z(cp, p, g, var)) {
1396 if (divide_in_z(g, q, cb ? *cb : dummy, var)) {
1400 ex lc = g.lcoeff(x);
1401 if (is_ex_exactly_of_type(lc, numeric) && ex_to_numeric(lc).is_negative())
1407 cq = interpolate(cq, xi, x);
1408 if (divide_in_z(cq, q, g, var)) {
1409 if (divide_in_z(g, p, ca ? *ca : dummy, var)) {
1413 ex lc = g.lcoeff(x);
1414 if (is_ex_exactly_of_type(lc, numeric) && ex_to_numeric(lc).is_negative())
1423 // Next evaluation point
1424 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1426 return *new ex(fail());
1430 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1433 * @param a first multivariate polynomial
1434 * @param b second multivariate polynomial
1435 * @param check_args check whether a and b are polynomials with rational
1436 * coefficients (defaults to "true")
1437 * @return the GCD as a new expression */
1438 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1440 //clog << "gcd(" << a << "," << b << ")\n";
1445 // GCD of numerics -> CLN
1446 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1447 numeric g = gcd(ex_to_numeric(a), ex_to_numeric(b));
1449 *ca = ex_to_numeric(a) / g;
1451 *cb = ex_to_numeric(b) / g;
1456 if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)) {
1457 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1460 // Partially factored cases (to avoid expanding large expressions)
1461 if (is_ex_exactly_of_type(a, mul)) {
1462 if (is_ex_exactly_of_type(b, mul) && b.nops() > a.nops())
1468 for (unsigned i=0; i<a.nops(); i++) {
1469 ex part_ca, part_cb;
1470 g *= gcd(a.op(i), part_b, &part_ca, &part_cb, check_args);
1479 } else if (is_ex_exactly_of_type(b, mul)) {
1480 if (is_ex_exactly_of_type(a, mul) && a.nops() > b.nops())
1486 for (unsigned i=0; i<b.nops(); i++) {
1487 ex part_ca, part_cb;
1488 g *= gcd(part_a, b.op(i), &part_ca, &part_cb, check_args);
1500 // Input polynomials of the form poly^n are sometimes also trivial
1501 if (is_ex_exactly_of_type(a, power)) {
1503 if (is_ex_exactly_of_type(b, power)) {
1504 if (p.is_equal(b.op(0))) {
1505 // a = p^n, b = p^m, gcd = p^min(n, m)
1506 ex exp_a = a.op(1), exp_b = b.op(1);
1507 if (exp_a < exp_b) {
1511 *cb = power(p, exp_b - exp_a);
1512 return power(p, exp_a);
1515 *ca = power(p, exp_a - exp_b);
1518 return power(p, exp_b);
1522 if (p.is_equal(b)) {
1523 // a = p^n, b = p, gcd = p
1525 *ca = power(p, a.op(1) - 1);
1531 } else if (is_ex_exactly_of_type(b, power)) {
1533 if (p.is_equal(a)) {
1534 // a = p, b = p^n, gcd = p
1538 *cb = power(p, b.op(1) - 1);
1544 // Some trivial cases
1545 ex aex = a.expand(), bex = b.expand();
1546 if (aex.is_zero()) {
1553 if (bex.is_zero()) {
1560 if (aex.is_equal(_ex1()) || bex.is_equal(_ex1())) {
1568 if (a.is_equal(b)) {
1577 // Gather symbol statistics
1578 sym_desc_vec sym_stats;
1579 get_symbol_stats(a, b, sym_stats);
1581 // The symbol with least degree is our main variable
1582 sym_desc_vec::const_iterator var = sym_stats.begin();
1583 const symbol &x = *(var->sym);
1585 // Cancel trivial common factor
1586 int ldeg_a = var->ldeg_a;
1587 int ldeg_b = var->ldeg_b;
1588 int min_ldeg = min(ldeg_a, ldeg_b);
1590 ex common = power(x, min_ldeg);
1591 //clog << "trivial common factor " << common << endl;
1592 return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1595 // Try to eliminate variables
1596 if (var->deg_a == 0) {
1597 //clog << "eliminating variable " << x << " from b" << endl;
1598 ex c = bex.content(x);
1599 ex g = gcd(aex, c, ca, cb, false);
1601 *cb *= bex.unit(x) * bex.primpart(x, c);
1603 } else if (var->deg_b == 0) {
1604 //clog << "eliminating variable " << x << " from a" << endl;
1605 ex c = aex.content(x);
1606 ex g = gcd(c, bex, ca, cb, false);
1608 *ca *= aex.unit(x) * aex.primpart(x, c);
1614 // Try heuristic algorithm first, fall back to PRS if that failed
1616 g = heur_gcd(aex, bex, ca, cb, var);
1617 } catch (gcdheu_failed) {
1618 g = *new ex(fail());
1620 if (is_ex_exactly_of_type(g, fail)) {
1621 //clog << "heuristics failed" << endl;
1626 // g = heur_gcd(aex, bex, ca, cb, var);
1627 // g = eu_gcd(aex, bex, &x);
1628 // g = euprem_gcd(aex, bex, &x);
1629 // g = peu_gcd(aex, bex, &x);
1630 // g = red_gcd(aex, bex, &x);
1631 g = sr_gcd(aex, bex, var);
1632 if (g.is_equal(_ex1())) {
1633 // Keep cofactors factored if possible
1640 divide(aex, g, *ca, false);
1642 divide(bex, g, *cb, false);
1646 if (g.is_equal(_ex1())) {
1647 // Keep cofactors factored if possible
1659 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1661 * @param a first multivariate polynomial
1662 * @param b second multivariate polynomial
1663 * @param check_args check whether a and b are polynomials with rational
1664 * coefficients (defaults to "true")
1665 * @return the LCM as a new expression */
1666 ex lcm(const ex &a, const ex &b, bool check_args)
1668 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
1669 return lcm(ex_to_numeric(a), ex_to_numeric(b));
1670 if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1671 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1674 ex g = gcd(a, b, &ca, &cb, false);
1680 * Square-free factorization
1683 // Univariate GCD of polynomials in Q[x] (used internally by sqrfree()).
1684 // a and b can be multivariate polynomials but they are treated as univariate polynomials in x.
1685 static ex univariate_gcd(const ex &a, const ex &b, const symbol &x)
1691 if (a.is_equal(_ex1()) || b.is_equal(_ex1()))
1693 if (is_ex_of_type(a, numeric) && is_ex_of_type(b, numeric))
1694 return gcd(ex_to_numeric(a), ex_to_numeric(b));
1695 if (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1696 throw(std::invalid_argument("univariate_gcd: arguments must be polynomials over the rationals"));
1698 // Euclidean algorithm
1700 if (a.degree(x) >= b.degree(x)) {
1708 r = rem(c, d, x, false);
1714 return d / d.lcoeff(x);
1718 /** Compute square-free factorization of multivariate polynomial a(x) using
1721 * @param a multivariate polynomial
1722 * @param x variable to factor in
1723 * @return factored polynomial */
1724 ex sqrfree(const ex &a, const symbol &x)
1729 ex c = univariate_gcd(a, b, x);
1731 if (c.is_equal(_ex1())) {
1735 ex y = quo(b, c, x);
1736 ex z = y - w.diff(x);
1737 while (!z.is_zero()) {
1738 ex g = univariate_gcd(w, z, x);
1746 return res * power(w, i);
1751 * Normal form of rational functions
1755 * Note: The internal normal() functions (= basic::normal() and overloaded
1756 * functions) all return lists of the form {numerator, denominator}. This
1757 * is to get around mul::eval()'s automatic expansion of numeric coefficients.
1758 * E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
1759 * the information that (a+b) is the numerator and 3 is the denominator.
1762 /** Create a symbol for replacing the expression "e" (or return a previously
1763 * assigned symbol). The symbol is appended to sym_lst and returned, the
1764 * expression is appended to repl_lst.
1765 * @see ex::normal */
1766 static ex replace_with_symbol(const ex &e, lst &sym_lst, lst &repl_lst)
1768 // Expression already in repl_lst? Then return the assigned symbol
1769 for (unsigned i=0; i<repl_lst.nops(); i++)
1770 if (repl_lst.op(i).is_equal(e))
1771 return sym_lst.op(i);
1773 // Otherwise create new symbol and add to list, taking care that the
1774 // replacement expression doesn't contain symbols from the sym_lst
1775 // because subs() is not recursive
1778 ex e_replaced = e.subs(sym_lst, repl_lst);
1780 repl_lst.append(e_replaced);
1784 /** Create a symbol for replacing the expression "e" (or return a previously
1785 * assigned symbol). An expression of the form "symbol == expression" is added
1786 * to repl_lst and the symbol is returned.
1787 * @see ex::to_rational */
1788 static ex replace_with_symbol(const ex &e, lst &repl_lst)
1790 // Expression already in repl_lst? Then return the assigned symbol
1791 for (unsigned i=0; i<repl_lst.nops(); i++)
1792 if (repl_lst.op(i).op(1).is_equal(e))
1793 return repl_lst.op(i).op(0);
1795 // Otherwise create new symbol and add to list, taking care that the
1796 // replacement expression doesn't contain symbols from the sym_lst
1797 // because subs() is not recursive
1800 ex e_replaced = e.subs(repl_lst);
1801 repl_lst.append(es == e_replaced);
1805 /** Default implementation of ex::normal(). It replaces the object with a
1807 * @see ex::normal */
1808 ex basic::normal(lst &sym_lst, lst &repl_lst, int level) const
1810 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1814 /** Implementation of ex::normal() for symbols. This returns the unmodified symbol.
1815 * @see ex::normal */
1816 ex symbol::normal(lst &sym_lst, lst &repl_lst, int level) const
1818 return (new lst(*this, _ex1()))->setflag(status_flags::dynallocated);
1822 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1823 * into re+I*im and replaces I and non-rational real numbers with a temporary
1825 * @see ex::normal */
1826 ex numeric::normal(lst &sym_lst, lst &repl_lst, int level) const
1828 numeric num = numer();
1831 if (num.is_real()) {
1832 if (!num.is_integer())
1833 numex = replace_with_symbol(numex, sym_lst, repl_lst);
1835 numeric re = num.real(), im = num.imag();
1836 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, sym_lst, repl_lst);
1837 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, sym_lst, repl_lst);
1838 numex = re_ex + im_ex * replace_with_symbol(I, sym_lst, repl_lst);
1841 // Denominator is always a real integer (see numeric::denom())
1842 return (new lst(numex, denom()))->setflag(status_flags::dynallocated);
1846 /** Fraction cancellation.
1847 * @param n numerator
1848 * @param d denominator
1849 * @return cancelled fraction {n, d} as a list */
1850 static ex frac_cancel(const ex &n, const ex &d)
1854 numeric pre_factor = _num1();
1856 //clog << "frac_cancel num = " << num << ", den = " << den << endl;
1858 // Handle special cases where numerator or denominator is 0
1860 return (new lst(_ex0(), _ex1()))->setflag(status_flags::dynallocated);
1861 if (den.expand().is_zero())
1862 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
1864 // Bring numerator and denominator to Z[X] by multiplying with
1865 // LCM of all coefficients' denominators
1866 numeric num_lcm = lcm_of_coefficients_denominators(num);
1867 numeric den_lcm = lcm_of_coefficients_denominators(den);
1868 num = multiply_lcm(num, num_lcm);
1869 den = multiply_lcm(den, den_lcm);
1870 pre_factor = den_lcm / num_lcm;
1872 // Cancel GCD from numerator and denominator
1874 if (gcd(num, den, &cnum, &cden, false) != _ex1()) {
1879 // Make denominator unit normal (i.e. coefficient of first symbol
1880 // as defined by get_first_symbol() is made positive)
1882 if (get_first_symbol(den, x)) {
1883 GINAC_ASSERT(is_ex_exactly_of_type(den.unit(*x),numeric));
1884 if (ex_to_numeric(den.unit(*x)).is_negative()) {
1890 // Return result as list
1891 //clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << endl;
1892 return (new lst(num * pre_factor.numer(), den * pre_factor.denom()))->setflag(status_flags::dynallocated);
1896 /** Implementation of ex::normal() for a sum. It expands terms and performs
1897 * fractional addition.
1898 * @see ex::normal */
1899 ex add::normal(lst &sym_lst, lst &repl_lst, int level) const
1902 return (new lst(*this, _ex1()))->setflag(status_flags::dynallocated);
1903 else if (level == -max_recursion_level)
1904 throw(std::runtime_error("max recursion level reached"));
1906 // Normalize and expand children, chop into summands
1908 o.reserve(seq.size()+1);
1909 epvector::const_iterator it = seq.begin(), itend = seq.end();
1910 while (it != itend) {
1912 // Normalize and expand child
1913 ex n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1).expand();
1915 // If numerator is a sum, chop into summands
1916 if (is_ex_exactly_of_type(n.op(0), add)) {
1917 epvector::const_iterator bit = ex_to_add(n.op(0)).seq.begin(), bitend = ex_to_add(n.op(0)).seq.end();
1918 while (bit != bitend) {
1919 o.push_back((new lst(recombine_pair_to_ex(*bit), n.op(1)))->setflag(status_flags::dynallocated));
1923 // The overall_coeff is already normalized (== rational), we just
1924 // split it into numerator and denominator
1925 GINAC_ASSERT(ex_to_numeric(ex_to_add(n.op(0)).overall_coeff).is_rational());
1926 numeric overall = ex_to_numeric(ex_to_add(n.op(0)).overall_coeff);
1927 o.push_back((new lst(overall.numer(), overall.denom() * n.op(1)))->setflag(status_flags::dynallocated));
1932 o.push_back(overall_coeff.bp->normal(sym_lst, repl_lst, level-1));
1934 // o is now a vector of {numerator, denominator} lists
1936 // Determine common denominator
1938 exvector::const_iterator ait = o.begin(), aitend = o.end();
1939 //clog << "add::normal uses the following summands:\n";
1940 while (ait != aitend) {
1941 //clog << " num = " << ait->op(0) << ", den = " << ait->op(1) << endl;
1942 den = lcm(ait->op(1), den, false);
1945 //clog << " common denominator = " << den << endl;
1948 if (den.is_equal(_ex1())) {
1950 // Common denominator is 1, simply add all numerators
1952 for (ait=o.begin(); ait!=aitend; ait++) {
1953 num_seq.push_back(ait->op(0));
1955 return (new lst((new add(num_seq))->setflag(status_flags::dynallocated), den))->setflag(status_flags::dynallocated);
1959 // Perform fractional addition
1961 for (ait=o.begin(); ait!=aitend; ait++) {
1963 if (!divide(den, ait->op(1), q, false)) {
1964 // should not happen
1965 throw(std::runtime_error("invalid expression in add::normal, division failed"));
1967 num_seq.push_back((ait->op(0) * q).expand());
1969 ex num = (new add(num_seq))->setflag(status_flags::dynallocated);
1971 // Cancel common factors from num/den
1972 return frac_cancel(num, den);
1977 /** Implementation of ex::normal() for a product. It cancels common factors
1979 * @see ex::normal() */
1980 ex mul::normal(lst &sym_lst, lst &repl_lst, int level) const
1983 return (new lst(*this, _ex1()))->setflag(status_flags::dynallocated);
1984 else if (level == -max_recursion_level)
1985 throw(std::runtime_error("max recursion level reached"));
1987 // Normalize children, separate into numerator and denominator
1991 epvector::const_iterator it = seq.begin(), itend = seq.end();
1992 while (it != itend) {
1993 n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1);
1998 n = overall_coeff.bp->normal(sym_lst, repl_lst, level-1);
2002 // Perform fraction cancellation
2003 return frac_cancel(num, den);
2007 /** Implementation of ex::normal() for powers. It normalizes the basis,
2008 * distributes integer exponents to numerator and denominator, and replaces
2009 * non-integer powers by temporary symbols.
2010 * @see ex::normal */
2011 ex power::normal(lst &sym_lst, lst &repl_lst, int level) const
2014 return (new lst(*this, _ex1()))->setflag(status_flags::dynallocated);
2015 else if (level == -max_recursion_level)
2016 throw(std::runtime_error("max recursion level reached"));
2019 ex n = basis.bp->normal(sym_lst, repl_lst, level-1);
2021 if (exponent.info(info_flags::integer)) {
2023 if (exponent.info(info_flags::positive)) {
2025 // (a/b)^n -> {a^n, b^n}
2026 return (new lst(power(n.op(0), exponent), power(n.op(1), exponent)))->setflag(status_flags::dynallocated);
2028 } else if (exponent.info(info_flags::negative)) {
2030 // (a/b)^-n -> {b^n, a^n}
2031 return (new lst(power(n.op(1), -exponent), power(n.op(0), -exponent)))->setflag(status_flags::dynallocated);
2036 if (exponent.info(info_flags::positive)) {
2038 // (a/b)^x -> {sym((a/b)^x), 1}
2039 return (new lst(replace_with_symbol(power(n.op(0) / n.op(1), exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
2041 } else if (exponent.info(info_flags::negative)) {
2043 if (n.op(1).is_equal(_ex1())) {
2045 // a^-x -> {1, sym(a^x)}
2046 return (new lst(_ex1(), replace_with_symbol(power(n.op(0), -exponent), sym_lst, repl_lst)))->setflag(status_flags::dynallocated);
2050 // (a/b)^-x -> {sym((b/a)^x), 1}
2051 return (new lst(replace_with_symbol(power(n.op(1) / n.op(0), -exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
2054 } else { // exponent not numeric
2056 // (a/b)^x -> {sym((a/b)^x, 1}
2057 return (new lst(replace_with_symbol(power(n.op(0) / n.op(1), exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
2063 /** Implementation of ex::normal() for pseries. It normalizes each coefficient and
2064 * replaces the series by a temporary symbol.
2065 * @see ex::normal */
2066 ex pseries::normal(lst &sym_lst, lst &repl_lst, int level) const
2069 new_seq.reserve(seq.size());
2071 epvector::const_iterator it = seq.begin(), itend = seq.end();
2072 while (it != itend) {
2073 new_seq.push_back(expair(it->rest.normal(), it->coeff));
2076 ex n = pseries(relational(var,point), new_seq);
2077 return (new lst(replace_with_symbol(n, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
2081 /** Implementation of ex::normal() for relationals. It normalizes both sides.
2082 * @see ex::normal */
2083 ex relational::normal(lst &sym_lst, lst &repl_lst, int level) const
2085 return (new lst(relational(lh.normal(), rh.normal(), o), _ex1()))->setflag(status_flags::dynallocated);
2089 /** Normalization of rational functions.
2090 * This function converts an expression to its normal form
2091 * "numerator/denominator", where numerator and denominator are (relatively
2092 * prime) polynomials. Any subexpressions which are not rational functions
2093 * (like non-rational numbers, non-integer powers or functions like sin(),
2094 * cos() etc.) are replaced by temporary symbols which are re-substituted by
2095 * the (normalized) subexpressions before normal() returns (this way, any
2096 * expression can be treated as a rational function). normal() is applied
2097 * recursively to arguments of functions etc.
2099 * @param level maximum depth of recursion
2100 * @return normalized expression */
2101 ex ex::normal(int level) const
2103 lst sym_lst, repl_lst;
2105 ex e = bp->normal(sym_lst, repl_lst, level);
2106 GINAC_ASSERT(is_ex_of_type(e, lst));
2108 // Re-insert replaced symbols
2109 if (sym_lst.nops() > 0)
2110 e = e.subs(sym_lst, repl_lst);
2112 // Convert {numerator, denominator} form back to fraction
2113 return e.op(0) / e.op(1);
2116 /** Numerator of an expression. If the expression is not of the normal form
2117 * "numerator/denominator", it is first converted to this form and then the
2118 * numerator is returned.
2121 * @return numerator */
2122 ex ex::numer(void) const
2124 lst sym_lst, repl_lst;
2126 ex e = bp->normal(sym_lst, repl_lst, 0);
2127 GINAC_ASSERT(is_ex_of_type(e, lst));
2129 // Re-insert replaced symbols
2130 if (sym_lst.nops() > 0)
2131 return e.op(0).subs(sym_lst, repl_lst);
2136 /** Denominator of an expression. If the expression is not of the normal form
2137 * "numerator/denominator", it is first converted to this form and then the
2138 * denominator is returned.
2141 * @return denominator */
2142 ex ex::denom(void) const
2144 lst sym_lst, repl_lst;
2146 ex e = bp->normal(sym_lst, repl_lst, 0);
2147 GINAC_ASSERT(is_ex_of_type(e, lst));
2149 // Re-insert replaced symbols
2150 if (sym_lst.nops() > 0)
2151 return e.op(1).subs(sym_lst, repl_lst);
2157 /** Default implementation of ex::to_rational(). It replaces the object with a
2159 * @see ex::to_rational */
2160 ex basic::to_rational(lst &repl_lst) const
2162 return replace_with_symbol(*this, repl_lst);
2166 /** Implementation of ex::to_rational() for symbols. This returns the
2167 * unmodified symbol.
2168 * @see ex::to_rational */
2169 ex symbol::to_rational(lst &repl_lst) const
2175 /** Implementation of ex::to_rational() for a numeric. It splits complex
2176 * numbers into re+I*im and replaces I and non-rational real numbers with a
2178 * @see ex::to_rational */
2179 ex numeric::to_rational(lst &repl_lst) const
2183 return replace_with_symbol(*this, repl_lst);
2185 numeric re = real();
2186 numeric im = imag();
2187 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl_lst);
2188 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl_lst);
2189 return re_ex + im_ex * replace_with_symbol(I, repl_lst);
2195 /** Implementation of ex::to_rational() for powers. It replaces non-integer
2196 * powers by temporary symbols.
2197 * @see ex::to_rational */
2198 ex power::to_rational(lst &repl_lst) const
2200 if (exponent.info(info_flags::integer))
2201 return power(basis.to_rational(repl_lst), exponent);
2203 return replace_with_symbol(*this, repl_lst);
2207 /** Implementation of ex::to_rational() for expairseqs.
2208 * @see ex::to_rational */
2209 ex expairseq::to_rational(lst &repl_lst) const
2212 s.reserve(seq.size());
2213 for (epvector::const_iterator it=seq.begin(); it!=seq.end(); ++it) {
2214 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*it).to_rational(repl_lst)));
2215 // s.push_back(combine_ex_with_coeff_to_pair((*it).rest.to_rational(repl_lst),
2217 ex oc = overall_coeff.to_rational(repl_lst);
2218 if (oc.info(info_flags::numeric))
2219 return thisexpairseq(s, overall_coeff);
2220 else s.push_back(combine_ex_with_coeff_to_pair(oc,_ex1()));
2221 return thisexpairseq(s, default_overall_coeff());
2225 /** Rationalization of non-rational functions.
2226 * This function converts a general expression to a rational polynomial
2227 * by replacing all non-rational subexpressions (like non-rational numbers,
2228 * non-integer powers or functions like sin(), cos() etc.) to temporary
2229 * symbols. This makes it possible to use functions like gcd() and divide()
2230 * on non-rational functions by applying to_rational() on the arguments,
2231 * calling the desired function and re-substituting the temporary symbols
2232 * in the result. To make the last step possible, all temporary symbols and
2233 * their associated expressions are collected in the list specified by the
2234 * repl_lst parameter in the form {symbol == expression}, ready to be passed
2235 * as an argument to ex::subs().
2237 * @param repl_lst collects a list of all temporary symbols and their replacements
2238 * @return rationalized expression */
2239 ex ex::to_rational(lst &repl_lst) const
2241 return bp->to_rational(repl_lst);
2245 #ifndef NO_NAMESPACE_GINAC
2246 } // namespace GiNaC
2247 #endif // ndef NO_NAMESPACE_GINAC