3 * This file implements several functions that work on univariate and
4 * multivariate polynomials and rational functions.
5 * These functions include polynomial quotient and remainder, GCD and LCM
6 * computation, square-free factorization and rational function normalization. */
9 * GiNaC Copyright (C) 1999-2000 Johannes Gutenberg University Mainz, Germany
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
35 #include "expairseq.h"
44 #include "relational.h"
49 #ifndef NO_NAMESPACE_GINAC
51 #endif // ndef NO_NAMESPACE_GINAC
53 // If comparing expressions (ex::compare()) is fast, you can set this to 1.
54 // Some routines like quo(), rem() and gcd() will then return a quick answer
55 // when they are called with two identical arguments.
56 #define FAST_COMPARE 1
58 // Set this if you want divide_in_z() to use remembering
59 #define USE_REMEMBER 0
61 // Set this if you want divide_in_z() to use trial division followed by
62 // polynomial interpolation (usually slower except for very large problems)
63 #define USE_TRIAL_DIVISION 0
65 // Set this to enable some statistical output for the GCD routines
70 // Statistics variables
71 static int gcd_called = 0;
72 static int sr_gcd_called = 0;
73 static int heur_gcd_called = 0;
74 static int heur_gcd_failed = 0;
76 // Print statistics at end of program
77 static struct _stat_print {
80 cout << "gcd() called " << gcd_called << " times\n";
81 cout << "sr_gcd() called " << sr_gcd_called << " times\n";
82 cout << "heur_gcd() called " << heur_gcd_called << " times\n";
83 cout << "heur_gcd() failed " << heur_gcd_failed << " times\n";
89 /** Return pointer to first symbol found in expression. Due to GiNaCĀ“s
90 * internal ordering of terms, it may not be obvious which symbol this
91 * function returns for a given expression.
93 * @param e expression to search
94 * @param x pointer to first symbol found (returned)
95 * @return "false" if no symbol was found, "true" otherwise */
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) */
190 static void get_symbol_stats(const ex &a, const ex &b, sym_desc_vec &v)
192 collect_symbols(a.eval(), v); // eval() to expand assigned symbols
193 collect_symbols(b.eval(), v);
194 sym_desc_vec::iterator it = v.begin(), itend = v.end();
195 while (it != itend) {
196 int deg_a = a.degree(*(it->sym));
197 int deg_b = b.degree(*(it->sym));
200 it->max_deg = max(deg_a, deg_b);
201 it->ldeg_a = a.ldegree(*(it->sym));
202 it->ldeg_b = b.ldegree(*(it->sym));
205 sort(v.begin(), v.end());
207 clog << "Symbols:\n";
208 it = v.begin(); itend = v.end();
209 while (it != itend) {
210 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;
211 clog << " lcoeff_a=" << a.lcoeff(*(it->sym)) << ", lcoeff_b=" << b.lcoeff(*(it->sym)) << endl;
219 * Computation of LCM of denominators of coefficients of a polynomial
222 // Compute LCM of denominators of coefficients by going through the
223 // expression recursively (used internally by lcm_of_coefficients_denominators())
224 static numeric lcmcoeff(const ex &e, const numeric &l)
226 if (e.info(info_flags::rational))
227 return lcm(ex_to_numeric(e).denom(), l);
228 else if (is_ex_exactly_of_type(e, add)) {
230 for (unsigned i=0; i<e.nops(); i++)
231 c = lcmcoeff(e.op(i), c);
233 } else if (is_ex_exactly_of_type(e, mul)) {
235 for (unsigned i=0; i<e.nops(); i++)
236 c *= lcmcoeff(e.op(i), _num1());
238 } else if (is_ex_exactly_of_type(e, power))
239 return pow(lcmcoeff(e.op(0), l), ex_to_numeric(e.op(1)));
243 /** Compute LCM of denominators of coefficients of a polynomial.
244 * Given a polynomial with rational coefficients, this function computes
245 * the LCM of the denominators of all coefficients. This can be used
246 * to bring a polynomial from Q[X] to Z[X].
248 * @param e multivariate polynomial (need not be expanded)
249 * @return LCM of denominators of coefficients */
251 static numeric lcm_of_coefficients_denominators(const ex &e)
253 return lcmcoeff(e, _num1());
256 /** Bring polynomial from Q[X] to Z[X] by multiplying in the previously
257 * determined LCM of the coefficient's denominators.
259 * @param e multivariate polynomial (need not be expanded)
260 * @param lcm LCM to multiply in */
262 static ex multiply_lcm(const ex &e, const numeric &lcm)
264 if (is_ex_exactly_of_type(e, mul)) {
266 numeric lcm_accum = _num1();
267 for (unsigned i=0; i<e.nops(); i++) {
268 numeric op_lcm = lcmcoeff(e.op(i), _num1());
269 c *= multiply_lcm(e.op(i), op_lcm);
272 c *= lcm / lcm_accum;
274 } else if (is_ex_exactly_of_type(e, add)) {
276 for (unsigned i=0; i<e.nops(); i++)
277 c += multiply_lcm(e.op(i), lcm);
279 } else if (is_ex_exactly_of_type(e, power)) {
280 return pow(multiply_lcm(e.op(0), lcm.power(ex_to_numeric(e.op(1)).inverse())), e.op(1));
286 /** Compute the integer content (= GCD of all numeric coefficients) of an
287 * expanded polynomial.
289 * @param e expanded polynomial
290 * @return integer content */
292 numeric ex::integer_content(void) const
295 return bp->integer_content();
298 numeric basic::integer_content(void) const
303 numeric numeric::integer_content(void) const
308 numeric add::integer_content(void) const
310 epvector::const_iterator it = seq.begin();
311 epvector::const_iterator itend = seq.end();
313 while (it != itend) {
314 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
315 GINAC_ASSERT(is_ex_exactly_of_type(it->coeff,numeric));
316 c = gcd(ex_to_numeric(it->coeff), c);
319 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
320 c = gcd(ex_to_numeric(overall_coeff),c);
324 numeric mul::integer_content(void) const
326 #ifdef DO_GINAC_ASSERT
327 epvector::const_iterator it = seq.begin();
328 epvector::const_iterator itend = seq.end();
329 while (it != itend) {
330 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
333 #endif // def DO_GINAC_ASSERT
334 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
335 return abs(ex_to_numeric(overall_coeff));
340 * Polynomial quotients and remainders
343 /** Quotient q(x) of polynomials a(x) and b(x) in Q[x].
344 * It satisfies a(x)=b(x)*q(x)+r(x).
346 * @param a first polynomial in x (dividend)
347 * @param b second polynomial in x (divisor)
348 * @param x a and b are polynomials in x
349 * @param check_args check whether a and b are polynomials with rational
350 * coefficients (defaults to "true")
351 * @return quotient of a and b in Q[x] */
353 ex quo(const ex &a, const ex &b, const symbol &x, bool check_args)
356 throw(std::overflow_error("quo: division by zero"));
357 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
363 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
364 throw(std::invalid_argument("quo: arguments must be polynomials over the rationals"));
366 // Polynomial long division
371 int bdeg = b.degree(x);
372 int rdeg = r.degree(x);
373 ex blcoeff = b.expand().coeff(x, bdeg);
374 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
375 while (rdeg >= bdeg) {
376 ex term, rcoeff = r.coeff(x, rdeg);
377 if (blcoeff_is_numeric)
378 term = rcoeff / blcoeff;
380 if (!divide(rcoeff, blcoeff, term, false))
381 return *new ex(fail());
383 term *= power(x, rdeg - bdeg);
385 r -= (term * b).expand();
394 /** Remainder r(x) of polynomials a(x) and b(x) in Q[x].
395 * It satisfies a(x)=b(x)*q(x)+r(x).
397 * @param a first polynomial in x (dividend)
398 * @param b second polynomial in x (divisor)
399 * @param x a and b are polynomials in x
400 * @param check_args check whether a and b are polynomials with rational
401 * coefficients (defaults to "true")
402 * @return remainder of a(x) and b(x) in Q[x] */
404 ex rem(const ex &a, const ex &b, const symbol &x, bool check_args)
407 throw(std::overflow_error("rem: division by zero"));
408 if (is_ex_exactly_of_type(a, numeric)) {
409 if (is_ex_exactly_of_type(b, numeric))
418 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
419 throw(std::invalid_argument("rem: arguments must be polynomials over the rationals"));
421 // Polynomial long division
425 int bdeg = b.degree(x);
426 int rdeg = r.degree(x);
427 ex blcoeff = b.expand().coeff(x, bdeg);
428 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
429 while (rdeg >= bdeg) {
430 ex term, rcoeff = r.coeff(x, rdeg);
431 if (blcoeff_is_numeric)
432 term = rcoeff / blcoeff;
434 if (!divide(rcoeff, blcoeff, term, false))
435 return *new ex(fail());
437 term *= power(x, rdeg - bdeg);
438 r -= (term * b).expand();
447 /** Pseudo-remainder of polynomials a(x) and b(x) in Z[x].
449 * @param a first polynomial in x (dividend)
450 * @param b second polynomial in x (divisor)
451 * @param x a and b are polynomials in x
452 * @param check_args check whether a and b are polynomials with rational
453 * coefficients (defaults to "true")
454 * @return pseudo-remainder of a(x) and b(x) in Z[x] */
456 ex prem(const ex &a, const ex &b, const symbol &x, bool check_args)
459 throw(std::overflow_error("prem: division by zero"));
460 if (is_ex_exactly_of_type(a, numeric)) {
461 if (is_ex_exactly_of_type(b, numeric))
466 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
467 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
469 // Polynomial long division
472 int rdeg = r.degree(x);
473 int bdeg = eb.degree(x);
476 blcoeff = eb.coeff(x, bdeg);
480 eb -= blcoeff * power(x, bdeg);
484 int delta = rdeg - bdeg + 1, i = 0;
485 while (rdeg >= bdeg && !r.is_zero()) {
486 ex rlcoeff = r.coeff(x, rdeg);
487 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
491 r -= rlcoeff * power(x, rdeg);
492 r = (blcoeff * r).expand() - term;
496 return power(blcoeff, delta - i) * r;
500 /** Exact polynomial division of a(X) by b(X) in Q[X].
502 * @param a first multivariate polynomial (dividend)
503 * @param b second multivariate polynomial (divisor)
504 * @param q quotient (returned)
505 * @param check_args check whether a and b are polynomials with rational
506 * coefficients (defaults to "true")
507 * @return "true" when exact division succeeds (quotient returned in q),
508 * "false" otherwise */
510 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
514 throw(std::overflow_error("divide: division by zero"));
517 if (is_ex_exactly_of_type(b, numeric)) {
520 } else if (is_ex_exactly_of_type(a, numeric))
528 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
529 throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
533 if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
534 throw(std::invalid_argument("invalid expression in divide()"));
536 // Polynomial long division (recursive)
540 int bdeg = b.degree(*x);
541 int rdeg = r.degree(*x);
542 ex blcoeff = b.expand().coeff(*x, bdeg);
543 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
544 while (rdeg >= bdeg) {
545 ex term, rcoeff = r.coeff(*x, rdeg);
546 if (blcoeff_is_numeric)
547 term = rcoeff / blcoeff;
549 if (!divide(rcoeff, blcoeff, term, false))
551 term *= power(*x, rdeg - bdeg);
553 r -= (term * b).expand();
567 typedef pair<ex, ex> ex2;
568 typedef pair<ex, bool> exbool;
571 bool operator() (const ex2 p, const ex2 q) const
573 return p.first.compare(q.first) < 0 || (!(q.first.compare(p.first) < 0) && p.second.compare(q.second) < 0);
577 typedef map<ex2, exbool, ex2_less> ex2_exbool_remember;
581 /** Exact polynomial division of a(X) by b(X) in Z[X].
582 * This functions works like divide() but the input and output polynomials are
583 * in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
584 * divide(), it doesnĀ“t check whether the input polynomials really are integer
585 * polynomials, so be careful of what you pass in. Also, you have to run
586 * get_symbol_stats() over the input polynomials before calling this function
587 * and pass an iterator to the first element of the sym_desc vector. This
588 * function is used internally by the heur_gcd().
590 * @param a first multivariate polynomial (dividend)
591 * @param b second multivariate polynomial (divisor)
592 * @param q quotient (returned)
593 * @param var iterator to first element of vector of sym_desc structs
594 * @return "true" when exact division succeeds (the quotient is returned in
595 * q), "false" otherwise.
596 * @see get_symbol_stats, heur_gcd */
597 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
601 throw(std::overflow_error("divide_in_z: division by zero"));
602 if (b.is_equal(_ex1())) {
606 if (is_ex_exactly_of_type(a, numeric)) {
607 if (is_ex_exactly_of_type(b, numeric)) {
609 return q.info(info_flags::integer);
622 static ex2_exbool_remember dr_remember;
623 ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
624 if (remembered != dr_remember.end()) {
625 q = remembered->second.first;
626 return remembered->second.second;
631 const symbol *x = var->sym;
634 int adeg = a.degree(*x), bdeg = b.degree(*x);
638 #if USE_TRIAL_DIVISION
640 // Trial division with polynomial interpolation
643 // Compute values at evaluation points 0..adeg
644 vector<numeric> alpha; alpha.reserve(adeg + 1);
645 exvector u; u.reserve(adeg + 1);
646 numeric point = _num0();
648 for (i=0; i<=adeg; i++) {
649 ex bs = b.subs(*x == point);
650 while (bs.is_zero()) {
652 bs = b.subs(*x == point);
654 if (!divide_in_z(a.subs(*x == point), bs, c, var+1))
656 alpha.push_back(point);
662 vector<numeric> rcp; rcp.reserve(adeg + 1);
663 rcp.push_back(_num0());
664 for (k=1; k<=adeg; k++) {
665 numeric product = alpha[k] - alpha[0];
667 product *= alpha[k] - alpha[i];
668 rcp.push_back(product.inverse());
671 // Compute Newton coefficients
672 exvector v; v.reserve(adeg + 1);
674 for (k=1; k<=adeg; k++) {
676 for (i=k-2; i>=0; i--)
677 temp = temp * (alpha[k] - alpha[i]) + v[i];
678 v.push_back((u[k] - temp) * rcp[k]);
681 // Convert from Newton form to standard form
683 for (k=adeg-1; k>=0; k--)
684 c = c * (*x - alpha[k]) + v[k];
686 if (c.degree(*x) == (adeg - bdeg)) {
694 // Polynomial long division (recursive)
700 ex blcoeff = eb.coeff(*x, bdeg);
701 while (rdeg >= bdeg) {
702 ex term, rcoeff = r.coeff(*x, rdeg);
703 if (!divide_in_z(rcoeff, blcoeff, term, var+1))
705 term = (term * power(*x, rdeg - bdeg)).expand();
707 r -= (term * eb).expand();
710 dr_remember[ex2(a, b)] = exbool(q, true);
717 dr_remember[ex2(a, b)] = exbool(q, false);
726 * Separation of unit part, content part and primitive part of polynomials
729 /** Compute unit part (= sign of leading coefficient) of a multivariate
730 * polynomial in Z[x]. The product of unit part, content part, and primitive
731 * part is the polynomial itself.
733 * @param x variable in which to compute the unit part
735 * @see ex::content, ex::primpart */
736 ex ex::unit(const symbol &x) const
738 ex c = expand().lcoeff(x);
739 if (is_ex_exactly_of_type(c, numeric))
740 return c < _ex0() ? _ex_1() : _ex1();
743 if (get_first_symbol(c, y))
746 throw(std::invalid_argument("invalid expression in unit()"));
751 /** Compute content part (= unit normal GCD of all coefficients) of a
752 * multivariate polynomial in Z[x]. The product of unit part, content part,
753 * and primitive part is the polynomial itself.
755 * @param x variable in which to compute the content part
756 * @return content part
757 * @see ex::unit, ex::primpart */
758 ex ex::content(const symbol &x) const
762 if (is_ex_exactly_of_type(*this, numeric))
763 return info(info_flags::negative) ? -*this : *this;
768 // First, try the integer content
769 ex c = e.integer_content();
771 ex lcoeff = r.lcoeff(x);
772 if (lcoeff.info(info_flags::integer))
775 // GCD of all coefficients
776 int deg = e.degree(x);
777 int ldeg = e.ldegree(x);
779 return e.lcoeff(x) / e.unit(x);
781 for (int i=ldeg; i<=deg; i++)
782 c = gcd(e.coeff(x, i), c, NULL, NULL, false);
787 /** Compute primitive part of a multivariate polynomial in Z[x].
788 * The product of unit part, content part, and primitive part is the
791 * @param x variable in which to compute the primitive part
792 * @return primitive part
793 * @see ex::unit, ex::content */
794 ex ex::primpart(const symbol &x) const
798 if (is_ex_exactly_of_type(*this, numeric))
805 if (is_ex_exactly_of_type(c, numeric))
806 return *this / (c * u);
808 return quo(*this, c * u, x, false);
812 /** Compute primitive part of a multivariate polynomial in Z[x] when the
813 * content part is already known. This function is faster in computing the
814 * primitive part than the previous function.
816 * @param x variable in which to compute the primitive part
817 * @param c previously computed content part
818 * @return primitive part */
820 ex ex::primpart(const symbol &x, const ex &c) const
826 if (is_ex_exactly_of_type(*this, numeric))
830 if (is_ex_exactly_of_type(c, numeric))
831 return *this / (c * u);
833 return quo(*this, c * u, x, false);
838 * GCD of multivariate polynomials
841 /** Compute GCD of multivariate polynomials using the Euclidean PRS algorithm
842 * (not really suited for multivariate GCDs). This function is only provided
843 * for testing purposes.
845 * @param a first multivariate polynomial
846 * @param b second multivariate polynomial
847 * @param x pointer to symbol (main variable) in which to compute the GCD in
848 * @return the GCD as a new expression
851 static ex eu_gcd(const ex &a, const ex &b, const symbol *x)
853 //clog << "eu_gcd(" << a << "," << b << ")\n";
855 // Sort c and d so that c has higher degree
857 int adeg = a.degree(*x), bdeg = b.degree(*x);
866 // Euclidean algorithm
869 //clog << " d = " << d << endl;
870 r = rem(c, d, *x, false);
872 return d.primpart(*x);
879 /** Compute GCD of multivariate polynomials using the Euclidean PRS algorithm
880 * with pseudo-remainders ("World's Worst GCD Algorithm", staying in Z[X]).
881 * This function is only provided for testing purposes.
883 * @param a first multivariate polynomial
884 * @param b second multivariate polynomial
885 * @param x pointer to symbol (main variable) in which to compute the GCD in
886 * @return the GCD as a new expression
889 static ex euprem_gcd(const ex &a, const ex &b, const symbol *x)
891 //clog << "euprem_gcd(" << a << "," << b << ")\n";
893 // Sort c and d so that c has higher degree
895 int adeg = a.degree(*x), bdeg = b.degree(*x);
904 // Euclidean algorithm with pseudo-remainders
907 //clog << " d = " << d << endl;
908 r = prem(c, d, *x, false);
910 return d.primpart(*x);
917 /** Compute GCD of multivariate polynomials using the primitive Euclidean
918 * PRS algorithm (complete content removal at each step). This function is
919 * only provided for testing purposes.
921 * @param a first multivariate polynomial
922 * @param b second multivariate polynomial
923 * @param x pointer to symbol (main variable) in which to compute the GCD in
924 * @return the GCD as a new expression
927 static ex peu_gcd(const ex &a, const ex &b, const symbol *x)
929 //clog << "peu_gcd(" << a << "," << b << ")\n";
931 // Sort c and d so that c has higher degree
933 int adeg = a.degree(*x), bdeg = b.degree(*x);
945 // Remove content from c and d, to be attached to GCD later
946 ex cont_c = c.content(*x);
947 ex cont_d = d.content(*x);
948 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
951 c = c.primpart(*x, cont_c);
952 d = d.primpart(*x, cont_d);
954 // Euclidean algorithm with content removal
957 //clog << " d = " << d << endl;
958 r = prem(c, d, *x, false);
967 /** Compute GCD of multivariate polynomials using the reduced PRS algorithm.
968 * This function is only provided for testing purposes.
970 * @param a first multivariate polynomial
971 * @param b second multivariate polynomial
972 * @param x pointer to symbol (main variable) in which to compute the GCD in
973 * @return the GCD as a new expression
976 static ex red_gcd(const ex &a, const ex &b, const symbol *x)
978 //clog << "red_gcd(" << a << "," << b << ")\n";
980 // Sort c and d so that c has higher degree
982 int adeg = a.degree(*x), bdeg = b.degree(*x);
996 // Remove content from c and d, to be attached to GCD later
997 ex cont_c = c.content(*x);
998 ex cont_d = d.content(*x);
999 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1002 c = c.primpart(*x, cont_c);
1003 d = d.primpart(*x, cont_d);
1005 // First element of subresultant sequence
1007 int delta = cdeg - ddeg;
1010 // Calculate polynomial pseudo-remainder
1011 //clog << " d = " << d << endl;
1012 r = prem(c, d, *x, false);
1014 return gamma * d.primpart(*x);
1018 if (!divide(r, pow(ri, delta), d, false))
1019 throw(std::runtime_error("invalid expression in red_gcd(), division failed"));
1020 ddeg = d.degree(*x);
1022 if (is_ex_exactly_of_type(r, numeric))
1025 return gamma * r.primpart(*x);
1028 ri = c.expand().lcoeff(*x);
1029 delta = cdeg - ddeg;
1034 /** Compute GCD of multivariate polynomials using the subresultant PRS
1035 * algorithm. This function is used internally by gcd().
1037 * @param a first multivariate polynomial
1038 * @param b second multivariate polynomial
1039 * @param x pointer to symbol (main variable) in which to compute the GCD in
1040 * @return the GCD as a new expression
1043 static ex sr_gcd(const ex &a, const ex &b, const symbol *x)
1045 //clog << "sr_gcd(" << a << "," << b << ")\n";
1050 // Sort c and d so that c has higher degree
1052 int adeg = a.degree(*x), bdeg = b.degree(*x);
1066 // Remove content from c and d, to be attached to GCD later
1067 ex cont_c = c.content(*x);
1068 ex cont_d = d.content(*x);
1069 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1072 c = c.primpart(*x, cont_c);
1073 d = d.primpart(*x, cont_d);
1074 //clog << " content " << gamma << " removed, continuing with sr_gcd(" << c << "," << d << ")\n";
1076 // First element of subresultant sequence
1077 ex r = _ex0(), ri = _ex1(), psi = _ex1();
1078 int delta = cdeg - ddeg;
1081 // Calculate polynomial pseudo-remainder
1082 //clog << " start of loop, psi = " << psi << ", calculating pseudo-remainder...\n";
1083 //clog << " d = " << d << endl;
1084 r = prem(c, d, *x, false);
1086 return gamma * d.primpart(*x);
1089 //clog << " dividing...\n";
1090 if (!divide(r, ri * pow(psi, delta), d, false))
1091 throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
1092 ddeg = d.degree(*x);
1094 if (is_ex_exactly_of_type(r, numeric))
1097 return gamma * r.primpart(*x);
1100 // Next element of subresultant sequence
1101 //clog << " calculating next subresultant...\n";
1102 ri = c.expand().lcoeff(*x);
1106 divide(pow(ri, delta), pow(psi, delta-1), psi, false);
1107 delta = cdeg - ddeg;
1112 /** Return maximum (absolute value) coefficient of a polynomial.
1113 * This function is used internally by heur_gcd().
1115 * @param e expanded multivariate polynomial
1116 * @return maximum coefficient
1119 numeric ex::max_coefficient(void) const
1121 GINAC_ASSERT(bp!=0);
1122 return bp->max_coefficient();
1125 numeric basic::max_coefficient(void) const
1130 numeric numeric::max_coefficient(void) const
1135 numeric add::max_coefficient(void) const
1137 epvector::const_iterator it = seq.begin();
1138 epvector::const_iterator itend = seq.end();
1139 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1140 numeric cur_max = abs(ex_to_numeric(overall_coeff));
1141 while (it != itend) {
1143 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
1144 a = abs(ex_to_numeric(it->coeff));
1152 numeric mul::max_coefficient(void) const
1154 #ifdef DO_GINAC_ASSERT
1155 epvector::const_iterator it = seq.begin();
1156 epvector::const_iterator itend = seq.end();
1157 while (it != itend) {
1158 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
1161 #endif // def DO_GINAC_ASSERT
1162 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1163 return abs(ex_to_numeric(overall_coeff));
1167 /** Apply symmetric modular homomorphism to a multivariate polynomial.
1168 * This function is used internally by heur_gcd().
1170 * @param e expanded multivariate polynomial
1172 * @return mapped polynomial
1175 ex ex::smod(const numeric &xi) const
1177 GINAC_ASSERT(bp!=0);
1178 return bp->smod(xi);
1181 ex basic::smod(const numeric &xi) const
1186 ex numeric::smod(const numeric &xi) const
1188 #ifndef NO_NAMESPACE_GINAC
1189 return GiNaC::smod(*this, xi);
1190 #else // ndef NO_NAMESPACE_GINAC
1191 return ::smod(*this, xi);
1192 #endif // ndef NO_NAMESPACE_GINAC
1195 ex add::smod(const numeric &xi) const
1198 newseq.reserve(seq.size()+1);
1199 epvector::const_iterator it = seq.begin();
1200 epvector::const_iterator itend = seq.end();
1201 while (it != itend) {
1202 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
1203 #ifndef NO_NAMESPACE_GINAC
1204 numeric coeff = GiNaC::smod(ex_to_numeric(it->coeff), xi);
1205 #else // ndef NO_NAMESPACE_GINAC
1206 numeric coeff = ::smod(ex_to_numeric(it->coeff), xi);
1207 #endif // ndef NO_NAMESPACE_GINAC
1208 if (!coeff.is_zero())
1209 newseq.push_back(expair(it->rest, coeff));
1212 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1213 #ifndef NO_NAMESPACE_GINAC
1214 numeric coeff = GiNaC::smod(ex_to_numeric(overall_coeff), xi);
1215 #else // ndef NO_NAMESPACE_GINAC
1216 numeric coeff = ::smod(ex_to_numeric(overall_coeff), xi);
1217 #endif // ndef NO_NAMESPACE_GINAC
1218 return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
1221 ex mul::smod(const numeric &xi) const
1223 #ifdef DO_GINAC_ASSERT
1224 epvector::const_iterator it = seq.begin();
1225 epvector::const_iterator itend = seq.end();
1226 while (it != itend) {
1227 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
1230 #endif // def DO_GINAC_ASSERT
1231 mul * mulcopyp=new mul(*this);
1232 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1233 #ifndef NO_NAMESPACE_GINAC
1234 mulcopyp->overall_coeff = GiNaC::smod(ex_to_numeric(overall_coeff),xi);
1235 #else // ndef NO_NAMESPACE_GINAC
1236 mulcopyp->overall_coeff = ::smod(ex_to_numeric(overall_coeff),xi);
1237 #endif // ndef NO_NAMESPACE_GINAC
1238 mulcopyp->clearflag(status_flags::evaluated);
1239 mulcopyp->clearflag(status_flags::hash_calculated);
1240 return mulcopyp->setflag(status_flags::dynallocated);
1244 /** Exception thrown by heur_gcd() to signal failure. */
1245 class gcdheu_failed {};
1247 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1248 * get_symbol_stats() must have been called previously with the input
1249 * polynomials and an iterator to the first element of the sym_desc vector
1250 * passed in. This function is used internally by gcd().
1252 * @param a first multivariate polynomial (expanded)
1253 * @param b second multivariate polynomial (expanded)
1254 * @param ca cofactor of polynomial a (returned), NULL to suppress
1255 * calculation of cofactor
1256 * @param cb cofactor of polynomial b (returned), NULL to suppress
1257 * calculation of cofactor
1258 * @param var iterator to first element of vector of sym_desc structs
1259 * @return the GCD as a new expression
1261 * @exception gcdheu_failed() */
1263 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
1265 //clog << "heur_gcd(" << a << "," << b << ")\n";
1270 // GCD of two numeric values -> CLN
1271 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1272 numeric g = gcd(ex_to_numeric(a), ex_to_numeric(b));
1277 *ca = ex_to_numeric(a).mul(rg);
1279 *cb = ex_to_numeric(b).mul(rg);
1283 // The first symbol is our main variable
1284 const symbol *x = var->sym;
1286 // Remove integer content
1287 numeric gc = gcd(a.integer_content(), b.integer_content());
1288 numeric rgc = gc.inverse();
1291 int maxdeg = max(p.degree(*x), q.degree(*x));
1293 // Find evaluation point
1294 numeric mp = p.max_coefficient(), mq = q.max_coefficient();
1297 xi = mq * _num2() + _num2();
1299 xi = mp * _num2() + _num2();
1302 for (int t=0; t<6; t++) {
1303 if (xi.int_length() * maxdeg > 100000) {
1304 //clog << "giving up heur_gcd, xi.int_length = " << xi.int_length() << ", maxdeg = " << maxdeg << endl;
1305 throw gcdheu_failed();
1308 // Apply evaluation homomorphism and calculate GCD
1309 ex gamma = heur_gcd(p.subs(*x == xi), q.subs(*x == xi), NULL, NULL, var+1).expand();
1310 if (!is_ex_exactly_of_type(gamma, fail)) {
1312 // Reconstruct polynomial from GCD of mapped polynomials
1314 numeric rxi = xi.inverse();
1315 for (int i=0; !gamma.is_zero(); i++) {
1316 ex gi = gamma.smod(xi);
1317 g += gi * power(*x, i);
1318 gamma = (gamma - gi) * rxi;
1320 // Remove integer content
1321 g /= g.integer_content();
1323 // If the calculated polynomial divides both a and b, this is the GCD
1325 if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1327 ex lc = g.lcoeff(*x);
1328 if (is_ex_exactly_of_type(lc, numeric) && ex_to_numeric(lc).is_negative())
1335 // Next evaluation point
1336 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1338 return *new ex(fail());
1342 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1345 * @param a first multivariate polynomial
1346 * @param b second multivariate polynomial
1347 * @param check_args check whether a and b are polynomials with rational
1348 * coefficients (defaults to "true")
1349 * @return the GCD as a new expression */
1351 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1353 //clog << "gcd(" << a << "," << b << ")\n";
1358 // GCD of numerics -> CLN
1359 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1360 numeric g = gcd(ex_to_numeric(a), ex_to_numeric(b));
1362 *ca = ex_to_numeric(a) / g;
1364 *cb = ex_to_numeric(b) / g;
1369 if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)) {
1370 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1373 // Partially factored cases (to avoid expanding large expressions)
1374 if (is_ex_exactly_of_type(a, mul)) {
1375 if (is_ex_exactly_of_type(b, mul) && b.nops() > a.nops())
1381 for (unsigned i=0; i<a.nops(); i++) {
1382 ex part_ca, part_cb;
1383 g *= gcd(a.op(i), part_b, &part_ca, &part_cb, check_args);
1392 } else if (is_ex_exactly_of_type(b, mul)) {
1393 if (is_ex_exactly_of_type(a, mul) && a.nops() > b.nops())
1399 for (unsigned i=0; i<b.nops(); i++) {
1400 ex part_ca, part_cb;
1401 g *= gcd(part_a, b.op(i), &part_ca, &part_cb, check_args);
1413 // Input polynomials of the form poly^n are sometimes also trivial
1414 if (is_ex_exactly_of_type(a, power)) {
1416 if (is_ex_exactly_of_type(b, power)) {
1417 if (p.is_equal(b.op(0))) {
1418 // a = p^n, b = p^m, gcd = p^min(n, m)
1419 ex exp_a = a.op(1), exp_b = b.op(1);
1420 if (exp_a < exp_b) {
1424 *cb = power(p, exp_b - exp_a);
1425 return power(p, exp_a);
1428 *ca = power(p, exp_a - exp_b);
1431 return power(p, exp_b);
1435 if (p.is_equal(b)) {
1436 // a = p^n, b = p, gcd = p
1438 *ca = power(p, a.op(1) - 1);
1444 } else if (is_ex_exactly_of_type(b, power)) {
1446 if (p.is_equal(a)) {
1447 // a = p, b = p^n, gcd = p
1451 *cb = power(p, b.op(1) - 1);
1457 // Some trivial cases
1458 ex aex = a.expand(), bex = b.expand();
1459 if (aex.is_zero()) {
1466 if (bex.is_zero()) {
1473 if (aex.is_equal(_ex1()) || bex.is_equal(_ex1())) {
1481 if (a.is_equal(b)) {
1490 // Gather symbol statistics
1491 sym_desc_vec sym_stats;
1492 get_symbol_stats(a, b, sym_stats);
1494 // The symbol with least degree is our main variable
1495 sym_desc_vec::const_iterator var = sym_stats.begin();
1496 const symbol *x = var->sym;
1498 // Cancel trivial common factor
1499 int ldeg_a = var->ldeg_a;
1500 int ldeg_b = var->ldeg_b;
1501 int min_ldeg = min(ldeg_a, ldeg_b);
1503 ex common = power(*x, min_ldeg);
1504 //clog << "trivial common factor " << common << endl;
1505 return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1508 // Try to eliminate variables
1509 if (var->deg_a == 0) {
1510 //clog << "eliminating variable " << *x << " from b" << endl;
1511 ex c = bex.content(*x);
1512 ex g = gcd(aex, c, ca, cb, false);
1514 *cb *= bex.unit(*x) * bex.primpart(*x, c);
1516 } else if (var->deg_b == 0) {
1517 //clog << "eliminating variable " << *x << " from a" << endl;
1518 ex c = aex.content(*x);
1519 ex g = gcd(c, bex, ca, cb, false);
1521 *ca *= aex.unit(*x) * aex.primpart(*x, c);
1527 // Try heuristic algorithm first, fall back to PRS if that failed
1529 g = heur_gcd(aex, bex, ca, cb, var);
1530 } catch (gcdheu_failed) {
1531 g = *new ex(fail());
1533 if (is_ex_exactly_of_type(g, fail)) {
1534 //clog << "heuristics failed" << endl;
1539 // g = heur_gcd(aex, bex, ca, cb, var);
1540 // g = eu_gcd(aex, bex, x);
1541 // g = euprem_gcd(aex, bex, x);
1542 // g = peu_gcd(aex, bex, x);
1543 // g = red_gcd(aex, bex, x);
1544 g = sr_gcd(aex, bex, x);
1545 if (g.is_equal(_ex1())) {
1546 // Keep cofactors factored if possible
1553 divide(aex, g, *ca, false);
1555 divide(bex, g, *cb, false);
1559 if (g.is_equal(_ex1())) {
1560 // Keep cofactors factored if possible
1572 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1574 * @param a first multivariate polynomial
1575 * @param b second multivariate polynomial
1576 * @param check_args check whether a and b are polynomials with rational
1577 * coefficients (defaults to "true")
1578 * @return the LCM as a new expression */
1579 ex lcm(const ex &a, const ex &b, bool check_args)
1581 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
1582 return lcm(ex_to_numeric(a), ex_to_numeric(b));
1583 if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1584 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1587 ex g = gcd(a, b, &ca, &cb, false);
1593 * Square-free factorization
1596 // Univariate GCD of polynomials in Q[x] (used internally by sqrfree()).
1597 // a and b can be multivariate polynomials but they are treated as univariate polynomials in x.
1598 static ex univariate_gcd(const ex &a, const ex &b, const symbol &x)
1604 if (a.is_equal(_ex1()) || b.is_equal(_ex1()))
1606 if (is_ex_of_type(a, numeric) && is_ex_of_type(b, numeric))
1607 return gcd(ex_to_numeric(a), ex_to_numeric(b));
1608 if (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1609 throw(std::invalid_argument("univariate_gcd: arguments must be polynomials over the rationals"));
1611 // Euclidean algorithm
1613 if (a.degree(x) >= b.degree(x)) {
1621 r = rem(c, d, x, false);
1627 return d / d.lcoeff(x);
1631 /** Compute square-free factorization of multivariate polynomial a(x) using
1634 * @param a multivariate polynomial
1635 * @param x variable to factor in
1636 * @return factored polynomial */
1637 ex sqrfree(const ex &a, const symbol &x)
1642 ex c = univariate_gcd(a, b, x);
1644 if (c.is_equal(_ex1())) {
1648 ex y = quo(b, c, x);
1649 ex z = y - w.diff(x);
1650 while (!z.is_zero()) {
1651 ex g = univariate_gcd(w, z, x);
1659 return res * power(w, i);
1664 * Normal form of rational functions
1668 * Note: The internal normal() functions (= basic::normal() and overloaded
1669 * functions) all return lists of the form {numerator, denominator}. This
1670 * is to get around mul::eval()'s automatic expansion of numeric coefficients.
1671 * E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
1672 * the information that (a+b) is the numerator and 3 is the denominator.
1675 /** Create a symbol for replacing the expression "e" (or return a previously
1676 * assigned symbol). The symbol is appended to sym_lst and returned, the
1677 * expression is appended to repl_lst.
1678 * @see ex::normal */
1679 static ex replace_with_symbol(const ex &e, lst &sym_lst, lst &repl_lst)
1681 // Expression already in repl_lst? Then return the assigned symbol
1682 for (unsigned i=0; i<repl_lst.nops(); i++)
1683 if (repl_lst.op(i).is_equal(e))
1684 return sym_lst.op(i);
1686 // Otherwise create new symbol and add to list, taking care that the
1687 // replacement expression doesn't contain symbols from the sym_lst
1688 // because subs() is not recursive
1691 ex e_replaced = e.subs(sym_lst, repl_lst);
1693 repl_lst.append(e_replaced);
1697 /** Create a symbol for replacing the expression "e" (or return a previously
1698 * assigned symbol). An expression of the form "symbol == expression" is added
1699 * to repl_lst and the symbol is returned.
1700 * @see ex::to_rational */
1701 static ex replace_with_symbol(const ex &e, lst &repl_lst)
1703 // Expression already in repl_lst? Then return the assigned symbol
1704 for (unsigned i=0; i<repl_lst.nops(); i++)
1705 if (repl_lst.op(i).op(1).is_equal(e))
1706 return repl_lst.op(i).op(0);
1708 // Otherwise create new symbol and add to list, taking care that the
1709 // replacement expression doesn't contain symbols from the sym_lst
1710 // because subs() is not recursive
1713 ex e_replaced = e.subs(repl_lst);
1714 repl_lst.append(es == e_replaced);
1718 /** Default implementation of ex::normal(). It replaces the object with a
1720 * @see ex::normal */
1721 ex basic::normal(lst &sym_lst, lst &repl_lst, int level) const
1723 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1727 /** Implementation of ex::normal() for symbols. This returns the unmodified symbol.
1728 * @see ex::normal */
1729 ex symbol::normal(lst &sym_lst, lst &repl_lst, int level) const
1731 return (new lst(*this, _ex1()))->setflag(status_flags::dynallocated);
1735 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1736 * into re+I*im and replaces I and non-rational real numbers with a temporary
1738 * @see ex::normal */
1739 ex numeric::normal(lst &sym_lst, lst &repl_lst, int level) const
1741 numeric num = numer();
1744 if (num.is_real()) {
1745 if (!num.is_integer())
1746 numex = replace_with_symbol(numex, sym_lst, repl_lst);
1748 numeric re = num.real(), im = num.imag();
1749 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, sym_lst, repl_lst);
1750 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, sym_lst, repl_lst);
1751 numex = re_ex + im_ex * replace_with_symbol(I, sym_lst, repl_lst);
1754 // Denominator is always a real integer (see numeric::denom())
1755 return (new lst(numex, denom()))->setflag(status_flags::dynallocated);
1759 /** Fraction cancellation.
1760 * @param n numerator
1761 * @param d denominator
1762 * @return cancelled fraction {n, d} as a list */
1763 static ex frac_cancel(const ex &n, const ex &d)
1767 numeric pre_factor = _num1();
1769 //clog << "frac_cancel num = " << num << ", den = " << den << endl;
1771 // Handle special cases where numerator or denominator is 0
1773 return (new lst(_ex0(), _ex1()))->setflag(status_flags::dynallocated);
1774 if (den.expand().is_zero())
1775 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
1777 // Bring numerator and denominator to Z[X] by multiplying with
1778 // LCM of all coefficients' denominators
1779 numeric num_lcm = lcm_of_coefficients_denominators(num);
1780 numeric den_lcm = lcm_of_coefficients_denominators(den);
1781 num = multiply_lcm(num, num_lcm);
1782 den = multiply_lcm(den, den_lcm);
1783 pre_factor = den_lcm / num_lcm;
1785 // Cancel GCD from numerator and denominator
1787 if (gcd(num, den, &cnum, &cden, false) != _ex1()) {
1792 // Make denominator unit normal (i.e. coefficient of first symbol
1793 // as defined by get_first_symbol() is made positive)
1795 if (get_first_symbol(den, x)) {
1796 GINAC_ASSERT(is_ex_exactly_of_type(den.unit(*x),numeric));
1797 if (ex_to_numeric(den.unit(*x)).is_negative()) {
1803 // Return result as list
1804 //clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << endl;
1805 return (new lst(num * pre_factor.numer(), den * pre_factor.denom()))->setflag(status_flags::dynallocated);
1809 /** Implementation of ex::normal() for a sum. It expands terms and performs
1810 * fractional addition.
1811 * @see ex::normal */
1812 ex add::normal(lst &sym_lst, lst &repl_lst, int level) const
1814 // Normalize and expand children, chop into summands
1816 o.reserve(seq.size()+1);
1817 epvector::const_iterator it = seq.begin(), itend = seq.end();
1818 while (it != itend) {
1820 // Normalize and expand child
1821 ex n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1).expand();
1823 // If numerator is a sum, chop into summands
1824 if (is_ex_exactly_of_type(n.op(0), add)) {
1825 epvector::const_iterator bit = ex_to_add(n.op(0)).seq.begin(), bitend = ex_to_add(n.op(0)).seq.end();
1826 while (bit != bitend) {
1827 o.push_back((new lst(recombine_pair_to_ex(*bit), n.op(1)))->setflag(status_flags::dynallocated));
1831 // The overall_coeff is already normalized (== rational), we just
1832 // split it into numerator and denominator
1833 GINAC_ASSERT(ex_to_numeric(ex_to_add(n.op(0)).overall_coeff).is_rational());
1834 numeric overall = ex_to_numeric(ex_to_add(n.op(0)).overall_coeff);
1835 o.push_back((new lst(overall.numer(), overall.denom() * n.op(1)))->setflag(status_flags::dynallocated));
1840 o.push_back(overall_coeff.bp->normal(sym_lst, repl_lst, level-1));
1842 // o is now a vector of {numerator, denominator} lists
1844 // Determine common denominator
1846 exvector::const_iterator ait = o.begin(), aitend = o.end();
1847 //clog << "add::normal uses the following summands:\n";
1848 while (ait != aitend) {
1849 //clog << " num = " << ait->op(0) << ", den = " << ait->op(1) << endl;
1850 den = lcm(ait->op(1), den, false);
1853 //clog << " common denominator = " << den << endl;
1856 if (den.is_equal(_ex1())) {
1858 // Common denominator is 1, simply add all numerators
1860 for (ait=o.begin(); ait!=aitend; ait++) {
1861 num_seq.push_back(ait->op(0));
1863 return (new lst((new add(num_seq))->setflag(status_flags::dynallocated), den))->setflag(status_flags::dynallocated);
1867 // Perform fractional addition
1869 for (ait=o.begin(); ait!=aitend; ait++) {
1871 if (!divide(den, ait->op(1), q, false)) {
1872 // should not happen
1873 throw(std::runtime_error("invalid expression in add::normal, division failed"));
1875 num_seq.push_back((ait->op(0) * q).expand());
1877 ex num = (new add(num_seq))->setflag(status_flags::dynallocated);
1879 // Cancel common factors from num/den
1880 return frac_cancel(num, den);
1885 /** Implementation of ex::normal() for a product. It cancels common factors
1887 * @see ex::normal() */
1888 ex mul::normal(lst &sym_lst, lst &repl_lst, int level) const
1890 // Normalize children, separate into numerator and denominator
1894 epvector::const_iterator it = seq.begin(), itend = seq.end();
1895 while (it != itend) {
1896 n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1);
1901 n = overall_coeff.bp->normal(sym_lst, repl_lst, level-1);
1905 // Perform fraction cancellation
1906 return frac_cancel(num, den);
1910 /** Implementation of ex::normal() for powers. It normalizes the basis,
1911 * distributes integer exponents to numerator and denominator, and replaces
1912 * non-integer powers by temporary symbols.
1913 * @see ex::normal */
1914 ex power::normal(lst &sym_lst, lst &repl_lst, int level) const
1917 ex n = basis.bp->normal(sym_lst, repl_lst, level-1);
1919 if (exponent.info(info_flags::integer)) {
1921 if (exponent.info(info_flags::positive)) {
1923 // (a/b)^n -> {a^n, b^n}
1924 return (new lst(power(n.op(0), exponent), power(n.op(1), exponent)))->setflag(status_flags::dynallocated);
1926 } else if (exponent.info(info_flags::negative)) {
1928 // (a/b)^-n -> {b^n, a^n}
1929 return (new lst(power(n.op(1), -exponent), power(n.op(0), -exponent)))->setflag(status_flags::dynallocated);
1934 if (exponent.info(info_flags::positive)) {
1936 // (a/b)^x -> {sym((a/b)^x), 1}
1937 return (new lst(replace_with_symbol(power(n.op(0) / n.op(1), exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1939 } else if (exponent.info(info_flags::negative)) {
1941 if (n.op(1).is_equal(_ex1())) {
1943 // a^-x -> {1, sym(a^x)}
1944 return (new lst(_ex1(), replace_with_symbol(power(n.op(0), -exponent), sym_lst, repl_lst)))->setflag(status_flags::dynallocated);
1948 // (a/b)^-x -> {sym((b/a)^x), 1}
1949 return (new lst(replace_with_symbol(power(n.op(1) / n.op(0), -exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1952 } else { // exponent not numeric
1954 // (a/b)^x -> {sym((a/b)^x, 1}
1955 return (new lst(replace_with_symbol(power(n.op(0) / n.op(1), exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1961 /** Implementation of ex::normal() for pseries. It normalizes each coefficient and
1962 * replaces the series by a temporary symbol.
1963 * @see ex::normal */
1964 ex pseries::normal(lst &sym_lst, lst &repl_lst, int level) const
1967 new_seq.reserve(seq.size());
1969 epvector::const_iterator it = seq.begin(), itend = seq.end();
1970 while (it != itend) {
1971 new_seq.push_back(expair(it->rest.normal(), it->coeff));
1974 ex n = pseries(relational(var,point), new_seq);
1975 return (new lst(replace_with_symbol(n, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1979 /** Implementation of ex::normal() for relationals. It normalizes both sides.
1980 * @see ex::normal */
1981 ex relational::normal(lst &sym_lst, lst &repl_lst, int level) const
1983 return (new lst(relational(lh.normal(), rh.normal(), o), _ex1()))->setflag(status_flags::dynallocated);
1987 /** Normalization of rational functions.
1988 * This function converts an expression to its normal form
1989 * "numerator/denominator", where numerator and denominator are (relatively
1990 * prime) polynomials. Any subexpressions which are not rational functions
1991 * (like non-rational numbers, non-integer powers or functions like sin(),
1992 * cos() etc.) are replaced by temporary symbols which are re-substituted by
1993 * the (normalized) subexpressions before normal() returns (this way, any
1994 * expression can be treated as a rational function). normal() is applied
1995 * recursively to arguments of functions etc.
1997 * @param level maximum depth of recursion
1998 * @return normalized expression */
1999 ex ex::normal(int level) const
2001 lst sym_lst, repl_lst;
2003 ex e = bp->normal(sym_lst, repl_lst, level);
2004 GINAC_ASSERT(is_ex_of_type(e, lst));
2006 // Re-insert replaced symbols
2007 if (sym_lst.nops() > 0)
2008 e = e.subs(sym_lst, repl_lst);
2010 // Convert {numerator, denominator} form back to fraction
2011 return e.op(0) / e.op(1);
2014 /** Numerator of an expression. If the expression is not of the normal form
2015 * "numerator/denominator", it is first converted to this form and then the
2016 * numerator is returned.
2019 * @return numerator */
2020 ex ex::numer(void) const
2022 lst sym_lst, repl_lst;
2024 ex e = bp->normal(sym_lst, repl_lst, 0);
2025 GINAC_ASSERT(is_ex_of_type(e, lst));
2027 // Re-insert replaced symbols
2028 if (sym_lst.nops() > 0)
2029 return e.op(0).subs(sym_lst, repl_lst);
2034 /** Denominator of an expression. If the expression is not of the normal form
2035 * "numerator/denominator", it is first converted to this form and then the
2036 * denominator is returned.
2039 * @return denominator */
2040 ex ex::denom(void) const
2042 lst sym_lst, repl_lst;
2044 ex e = bp->normal(sym_lst, repl_lst, 0);
2045 GINAC_ASSERT(is_ex_of_type(e, lst));
2047 // Re-insert replaced symbols
2048 if (sym_lst.nops() > 0)
2049 return e.op(1).subs(sym_lst, repl_lst);
2055 /** Default implementation of ex::to_rational(). It replaces the object with a
2057 * @see ex::to_rational */
2058 ex basic::to_rational(lst &repl_lst) const
2060 return replace_with_symbol(*this, repl_lst);
2064 /** Implementation of ex::to_rational() for symbols. This returns the unmodified symbol.
2065 * @see ex::to_rational */
2066 ex symbol::to_rational(lst &repl_lst) const
2072 /** Implementation of ex::to_rational() for a numeric. It splits complex numbers
2073 * into re+I*im and replaces I and non-rational real numbers with a temporary
2075 * @see ex::to_rational */
2076 ex numeric::to_rational(lst &repl_lst) const
2080 return replace_with_symbol(*this, repl_lst);
2082 numeric re = real(), im = imag();
2083 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl_lst);
2084 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl_lst);
2085 return re_ex + im_ex * replace_with_symbol(I, repl_lst);
2091 /** Implementation of ex::to_rational() for powers. It replaces non-integer
2092 * powers by temporary symbols.
2093 * @see ex::to_rational */
2094 ex power::to_rational(lst &repl_lst) const
2096 if (exponent.info(info_flags::integer))
2097 return power(basis.to_rational(repl_lst), exponent);
2099 return replace_with_symbol(*this, repl_lst);
2103 /** Rationalization of non-rational functions.
2104 * This function converts a general expression to a rational polynomial
2105 * by replacing all non-rational subexpressions (like non-rational numbers,
2106 * non-integer powers or functions like sin(), cos() etc.) to temporary
2107 * symbols. This makes it possible to use functions like gcd() and divide()
2108 * on non-rational functions by applying to_rational() on the arguments,
2109 * calling the desired function and re-substituting the temporary symbols
2110 * in the result. To make the last step possible, all temporary symbols and
2111 * their associated expressions are collected in the list specified by the
2112 * repl_lst parameter in the form {symbol == expression}, ready to be passed
2113 * as an argument to ex::subs().
2115 * @param repl_lst collects a list of all temporary symbols and their replacements
2116 * @return rationalized expression */
2117 ex ex::to_rational(lst &repl_lst) const
2119 return bp->to_rational(repl_lst);
2123 #ifndef NO_NAMESPACE_GINAC
2124 } // namespace GiNaC
2125 #endif // ndef NO_NAMESPACE_GINAC