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 /** Minimum of ldeg_a and ldeg_b (Used for sorting) */
143 /** Commparison operator for sorting */
144 bool operator<(const sym_desc &x) const {return min_deg < x.min_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->min_deg = min(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());
210 * Computation of LCM of denominators of coefficients of a polynomial
213 // Compute LCM of denominators of coefficients by going through the
214 // expression recursively (used internally by lcm_of_coefficients_denominators())
215 static numeric lcmcoeff(const ex &e, const numeric &l)
217 if (e.info(info_flags::rational))
218 return lcm(ex_to_numeric(e).denom(), l);
219 else if (is_ex_exactly_of_type(e, add)) {
221 for (unsigned i=0; i<e.nops(); i++)
222 c = lcmcoeff(e.op(i), c);
224 } else if (is_ex_exactly_of_type(e, mul)) {
226 for (unsigned i=0; i<e.nops(); i++)
227 c *= lcmcoeff(e.op(i), _num1());
229 } else if (is_ex_exactly_of_type(e, power))
230 return pow(lcmcoeff(e.op(0), l), ex_to_numeric(e.op(1)));
234 /** Compute LCM of denominators of coefficients of a polynomial.
235 * Given a polynomial with rational coefficients, this function computes
236 * the LCM of the denominators of all coefficients. This can be used
237 * to bring a polynomial from Q[X] to Z[X].
239 * @param e multivariate polynomial (need not be expanded)
240 * @return LCM of denominators of coefficients */
242 static numeric lcm_of_coefficients_denominators(const ex &e)
244 return lcmcoeff(e, _num1());
247 /** Bring polynomial from Q[X] to Z[X] by multiplying in the previously
248 * determined LCM of the coefficient's denominators.
250 * @param e multivariate polynomial (need not be expanded)
251 * @param lcm LCM to multiply in */
253 static ex multiply_lcm(const ex &e, const numeric &lcm)
255 if (is_ex_exactly_of_type(e, mul)) {
257 numeric lcm_accum = _num1();
258 for (unsigned i=0; i<e.nops(); i++) {
259 numeric op_lcm = lcmcoeff(e.op(i), _num1());
260 c *= multiply_lcm(e.op(i), op_lcm);
263 c *= lcm / lcm_accum;
265 } else if (is_ex_exactly_of_type(e, add)) {
267 for (unsigned i=0; i<e.nops(); i++)
268 c += multiply_lcm(e.op(i), lcm);
270 } else if (is_ex_exactly_of_type(e, power)) {
271 return pow(multiply_lcm(e.op(0), lcm.power(ex_to_numeric(e.op(1)).inverse())), e.op(1));
277 /** Compute the integer content (= GCD of all numeric coefficients) of an
278 * expanded polynomial.
280 * @param e expanded polynomial
281 * @return integer content */
283 numeric ex::integer_content(void) const
286 return bp->integer_content();
289 numeric basic::integer_content(void) const
294 numeric numeric::integer_content(void) const
299 numeric add::integer_content(void) const
301 epvector::const_iterator it = seq.begin();
302 epvector::const_iterator itend = seq.end();
304 while (it != itend) {
305 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
306 GINAC_ASSERT(is_ex_exactly_of_type(it->coeff,numeric));
307 c = gcd(ex_to_numeric(it->coeff), c);
310 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
311 c = gcd(ex_to_numeric(overall_coeff),c);
315 numeric mul::integer_content(void) const
317 #ifdef DO_GINAC_ASSERT
318 epvector::const_iterator it = seq.begin();
319 epvector::const_iterator itend = seq.end();
320 while (it != itend) {
321 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
324 #endif // def DO_GINAC_ASSERT
325 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
326 return abs(ex_to_numeric(overall_coeff));
331 * Polynomial quotients and remainders
334 /** Quotient q(x) of polynomials a(x) and b(x) in Q[x].
335 * It satisfies a(x)=b(x)*q(x)+r(x).
337 * @param a first polynomial in x (dividend)
338 * @param b second polynomial in x (divisor)
339 * @param x a and b are polynomials in x
340 * @param check_args check whether a and b are polynomials with rational
341 * coefficients (defaults to "true")
342 * @return quotient of a and b in Q[x] */
344 ex quo(const ex &a, const ex &b, const symbol &x, bool check_args)
347 throw(std::overflow_error("quo: division by zero"));
348 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
354 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
355 throw(std::invalid_argument("quo: arguments must be polynomials over the rationals"));
357 // Polynomial long division
362 int bdeg = b.degree(x);
363 int rdeg = r.degree(x);
364 ex blcoeff = b.expand().coeff(x, bdeg);
365 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
366 while (rdeg >= bdeg) {
367 ex term, rcoeff = r.coeff(x, rdeg);
368 if (blcoeff_is_numeric)
369 term = rcoeff / blcoeff;
371 if (!divide(rcoeff, blcoeff, term, false))
372 return *new ex(fail());
374 term *= power(x, rdeg - bdeg);
376 r -= (term * b).expand();
385 /** Remainder r(x) of polynomials a(x) and b(x) in Q[x].
386 * It satisfies a(x)=b(x)*q(x)+r(x).
388 * @param a first polynomial in x (dividend)
389 * @param b second polynomial in x (divisor)
390 * @param x a and b are polynomials in x
391 * @param check_args check whether a and b are polynomials with rational
392 * coefficients (defaults to "true")
393 * @return remainder of a(x) and b(x) in Q[x] */
395 ex rem(const ex &a, const ex &b, const symbol &x, bool check_args)
398 throw(std::overflow_error("rem: division by zero"));
399 if (is_ex_exactly_of_type(a, numeric)) {
400 if (is_ex_exactly_of_type(b, numeric))
409 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
410 throw(std::invalid_argument("rem: arguments must be polynomials over the rationals"));
412 // Polynomial long division
416 int bdeg = b.degree(x);
417 int rdeg = r.degree(x);
418 ex blcoeff = b.expand().coeff(x, bdeg);
419 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
420 while (rdeg >= bdeg) {
421 ex term, rcoeff = r.coeff(x, rdeg);
422 if (blcoeff_is_numeric)
423 term = rcoeff / blcoeff;
425 if (!divide(rcoeff, blcoeff, term, false))
426 return *new ex(fail());
428 term *= power(x, rdeg - bdeg);
429 r -= (term * b).expand();
438 /** Pseudo-remainder of polynomials a(x) and b(x) in Z[x].
440 * @param a first polynomial in x (dividend)
441 * @param b second polynomial in x (divisor)
442 * @param x a and b are polynomials in x
443 * @param check_args check whether a and b are polynomials with rational
444 * coefficients (defaults to "true")
445 * @return pseudo-remainder of a(x) and b(x) in Z[x] */
447 ex prem(const ex &a, const ex &b, const symbol &x, bool check_args)
450 throw(std::overflow_error("prem: division by zero"));
451 if (is_ex_exactly_of_type(a, numeric)) {
452 if (is_ex_exactly_of_type(b, numeric))
457 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
458 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
460 // Polynomial long division
463 int rdeg = r.degree(x);
464 int bdeg = eb.degree(x);
467 blcoeff = eb.coeff(x, bdeg);
471 eb -= blcoeff * power(x, bdeg);
475 int delta = rdeg - bdeg + 1, i = 0;
476 while (rdeg >= bdeg && !r.is_zero()) {
477 ex rlcoeff = r.coeff(x, rdeg);
478 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
482 r -= rlcoeff * power(x, rdeg);
483 r = (blcoeff * r).expand() - term;
487 return power(blcoeff, delta - i) * r;
491 /** Exact polynomial division of a(X) by b(X) in Q[X].
493 * @param a first multivariate polynomial (dividend)
494 * @param b second multivariate polynomial (divisor)
495 * @param q quotient (returned)
496 * @param check_args check whether a and b are polynomials with rational
497 * coefficients (defaults to "true")
498 * @return "true" when exact division succeeds (quotient returned in q),
499 * "false" otherwise */
501 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
505 throw(std::overflow_error("divide: division by zero"));
506 if (is_ex_exactly_of_type(b, numeric)) {
509 } else if (is_ex_exactly_of_type(a, numeric))
517 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
518 throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
522 if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
523 throw(std::invalid_argument("invalid expression in divide()"));
525 // Polynomial long division (recursive)
529 int bdeg = b.degree(*x);
530 int rdeg = r.degree(*x);
531 ex blcoeff = b.expand().coeff(*x, bdeg);
532 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
533 while (rdeg >= bdeg) {
534 ex term, rcoeff = r.coeff(*x, rdeg);
535 if (blcoeff_is_numeric)
536 term = rcoeff / blcoeff;
538 if (!divide(rcoeff, blcoeff, term, false))
540 term *= power(*x, rdeg - bdeg);
542 r -= (term * b).expand();
556 typedef pair<ex, ex> ex2;
557 typedef pair<ex, bool> exbool;
560 bool operator() (const ex2 p, const ex2 q) const
562 return p.first.compare(q.first) < 0 || (!(q.first.compare(p.first) < 0) && p.second.compare(q.second) < 0);
566 typedef map<ex2, exbool, ex2_less> ex2_exbool_remember;
570 /** Exact polynomial division of a(X) by b(X) in Z[X].
571 * This functions works like divide() but the input and output polynomials are
572 * in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
573 * divide(), it doesn“t check whether the input polynomials really are integer
574 * polynomials, so be careful of what you pass in. Also, you have to run
575 * get_symbol_stats() over the input polynomials before calling this function
576 * and pass an iterator to the first element of the sym_desc vector. This
577 * function is used internally by the heur_gcd().
579 * @param a first multivariate polynomial (dividend)
580 * @param b second multivariate polynomial (divisor)
581 * @param q quotient (returned)
582 * @param var iterator to first element of vector of sym_desc structs
583 * @return "true" when exact division succeeds (the quotient is returned in
584 * q), "false" otherwise.
585 * @see get_symbol_stats, heur_gcd */
586 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
590 throw(std::overflow_error("divide_in_z: division by zero"));
591 if (b.is_equal(_ex1())) {
595 if (is_ex_exactly_of_type(a, numeric)) {
596 if (is_ex_exactly_of_type(b, numeric)) {
598 return q.info(info_flags::integer);
611 static ex2_exbool_remember dr_remember;
612 ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
613 if (remembered != dr_remember.end()) {
614 q = remembered->second.first;
615 return remembered->second.second;
620 const symbol *x = var->sym;
623 int adeg = a.degree(*x), bdeg = b.degree(*x);
627 #if USE_TRIAL_DIVISION
629 // Trial division with polynomial interpolation
632 // Compute values at evaluation points 0..adeg
633 vector<numeric> alpha; alpha.reserve(adeg + 1);
634 exvector u; u.reserve(adeg + 1);
635 numeric point = _num0();
637 for (i=0; i<=adeg; i++) {
638 ex bs = b.subs(*x == point);
639 while (bs.is_zero()) {
641 bs = b.subs(*x == point);
643 if (!divide_in_z(a.subs(*x == point), bs, c, var+1))
645 alpha.push_back(point);
651 vector<numeric> rcp; rcp.reserve(adeg + 1);
652 rcp.push_back(_num0());
653 for (k=1; k<=adeg; k++) {
654 numeric product = alpha[k] - alpha[0];
656 product *= alpha[k] - alpha[i];
657 rcp.push_back(product.inverse());
660 // Compute Newton coefficients
661 exvector v; v.reserve(adeg + 1);
663 for (k=1; k<=adeg; k++) {
665 for (i=k-2; i>=0; i--)
666 temp = temp * (alpha[k] - alpha[i]) + v[i];
667 v.push_back((u[k] - temp) * rcp[k]);
670 // Convert from Newton form to standard form
672 for (k=adeg-1; k>=0; k--)
673 c = c * (*x - alpha[k]) + v[k];
675 if (c.degree(*x) == (adeg - bdeg)) {
683 // Polynomial long division (recursive)
689 ex blcoeff = eb.coeff(*x, bdeg);
690 while (rdeg >= bdeg) {
691 ex term, rcoeff = r.coeff(*x, rdeg);
692 if (!divide_in_z(rcoeff, blcoeff, term, var+1))
694 term = (term * power(*x, rdeg - bdeg)).expand();
696 r -= (term * eb).expand();
699 dr_remember[ex2(a, b)] = exbool(q, true);
706 dr_remember[ex2(a, b)] = exbool(q, false);
715 * Separation of unit part, content part and primitive part of polynomials
718 /** Compute unit part (= sign of leading coefficient) of a multivariate
719 * polynomial in Z[x]. The product of unit part, content part, and primitive
720 * part is the polynomial itself.
722 * @param x variable in which to compute the unit part
724 * @see ex::content, ex::primpart */
725 ex ex::unit(const symbol &x) const
727 ex c = expand().lcoeff(x);
728 if (is_ex_exactly_of_type(c, numeric))
729 return c < _ex0() ? _ex_1() : _ex1();
732 if (get_first_symbol(c, y))
735 throw(std::invalid_argument("invalid expression in unit()"));
740 /** Compute content part (= unit normal GCD of all coefficients) of a
741 * multivariate polynomial in Z[x]. The product of unit part, content part,
742 * and primitive part is the polynomial itself.
744 * @param x variable in which to compute the content part
745 * @return content part
746 * @see ex::unit, ex::primpart */
747 ex ex::content(const symbol &x) const
751 if (is_ex_exactly_of_type(*this, numeric))
752 return info(info_flags::negative) ? -*this : *this;
757 // First, try the integer content
758 ex c = e.integer_content();
760 ex lcoeff = r.lcoeff(x);
761 if (lcoeff.info(info_flags::integer))
764 // GCD of all coefficients
765 int deg = e.degree(x);
766 int ldeg = e.ldegree(x);
768 return e.lcoeff(x) / e.unit(x);
770 for (int i=ldeg; i<=deg; i++)
771 c = gcd(e.coeff(x, i), c, NULL, NULL, false);
776 /** Compute primitive part of a multivariate polynomial in Z[x].
777 * The product of unit part, content part, and primitive part is the
780 * @param x variable in which to compute the primitive part
781 * @return primitive part
782 * @see ex::unit, ex::content */
783 ex ex::primpart(const symbol &x) const
787 if (is_ex_exactly_of_type(*this, numeric))
794 if (is_ex_exactly_of_type(c, numeric))
795 return *this / (c * u);
797 return quo(*this, c * u, x, false);
801 /** Compute primitive part of a multivariate polynomial in Z[x] when the
802 * content part is already known. This function is faster in computing the
803 * primitive part than the previous function.
805 * @param x variable in which to compute the primitive part
806 * @param c previously computed content part
807 * @return primitive part */
809 ex ex::primpart(const symbol &x, const ex &c) const
815 if (is_ex_exactly_of_type(*this, numeric))
819 if (is_ex_exactly_of_type(c, numeric))
820 return *this / (c * u);
822 return quo(*this, c * u, x, false);
827 * GCD of multivariate polynomials
830 /** Compute GCD of multivariate polynomials using the subresultant PRS
831 * algorithm. This function is used internally gy gcd().
833 * @param a first multivariate polynomial
834 * @param b second multivariate polynomial
835 * @param x pointer to symbol (main variable) in which to compute the GCD in
836 * @return the GCD as a new expression
839 static ex sr_gcd(const ex &a, const ex &b, const symbol *x)
841 //clog << "sr_gcd(" << a << "," << b << ")\n";
846 // Sort c and d so that c has higher degree
848 int adeg = a.degree(*x), bdeg = b.degree(*x);
862 // Remove content from c and d, to be attached to GCD later
863 ex cont_c = c.content(*x);
864 ex cont_d = d.content(*x);
865 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
868 c = c.primpart(*x, cont_c);
869 d = d.primpart(*x, cont_d);
870 //clog << " content " << gamma << " removed, continuing with sr_gcd(" << c << "," << d << ")\n";
872 // First element of subresultant sequence
873 ex r = _ex0(), ri = _ex1(), psi = _ex1();
874 int delta = cdeg - ddeg;
877 // Calculate polynomial pseudo-remainder
878 //clog << " start of loop, psi = " << psi << ", calculating pseudo-remainder...\n";
879 r = prem(c, d, *x, false);
881 return gamma * d.primpart(*x);
884 //clog << " dividing...\n";
885 if (!divide(r, ri * power(psi, delta), d, false))
886 throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
889 if (is_ex_exactly_of_type(r, numeric))
892 return gamma * r.primpart(*x);
895 // Next element of subresultant sequence
896 //clog << " calculating next subresultant...\n";
897 ri = c.expand().lcoeff(*x);
901 divide(power(ri, delta), power(psi, delta-1), psi, false);
907 /** Return maximum (absolute value) coefficient of a polynomial.
908 * This function is used internally by heur_gcd().
910 * @param e expanded multivariate polynomial
911 * @return maximum coefficient
914 numeric ex::max_coefficient(void) const
917 return bp->max_coefficient();
920 numeric basic::max_coefficient(void) const
925 numeric numeric::max_coefficient(void) const
930 numeric add::max_coefficient(void) const
932 epvector::const_iterator it = seq.begin();
933 epvector::const_iterator itend = seq.end();
934 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
935 numeric cur_max = abs(ex_to_numeric(overall_coeff));
936 while (it != itend) {
938 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
939 a = abs(ex_to_numeric(it->coeff));
947 numeric mul::max_coefficient(void) const
949 #ifdef DO_GINAC_ASSERT
950 epvector::const_iterator it = seq.begin();
951 epvector::const_iterator itend = seq.end();
952 while (it != itend) {
953 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
956 #endif // def DO_GINAC_ASSERT
957 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
958 return abs(ex_to_numeric(overall_coeff));
962 /** Apply symmetric modular homomorphism to a multivariate polynomial.
963 * This function is used internally by heur_gcd().
965 * @param e expanded multivariate polynomial
967 * @return mapped polynomial
970 ex ex::smod(const numeric &xi) const
976 ex basic::smod(const numeric &xi) const
981 ex numeric::smod(const numeric &xi) const
983 #ifndef NO_NAMESPACE_GINAC
984 return GiNaC::smod(*this, xi);
985 #else // ndef NO_NAMESPACE_GINAC
986 return ::smod(*this, xi);
987 #endif // ndef NO_NAMESPACE_GINAC
990 ex add::smod(const numeric &xi) const
993 newseq.reserve(seq.size()+1);
994 epvector::const_iterator it = seq.begin();
995 epvector::const_iterator itend = seq.end();
996 while (it != itend) {
997 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
998 #ifndef NO_NAMESPACE_GINAC
999 numeric coeff = GiNaC::smod(ex_to_numeric(it->coeff), xi);
1000 #else // ndef NO_NAMESPACE_GINAC
1001 numeric coeff = ::smod(ex_to_numeric(it->coeff), xi);
1002 #endif // ndef NO_NAMESPACE_GINAC
1003 if (!coeff.is_zero())
1004 newseq.push_back(expair(it->rest, coeff));
1007 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1008 #ifndef NO_NAMESPACE_GINAC
1009 numeric coeff = GiNaC::smod(ex_to_numeric(overall_coeff), xi);
1010 #else // ndef NO_NAMESPACE_GINAC
1011 numeric coeff = ::smod(ex_to_numeric(overall_coeff), xi);
1012 #endif // ndef NO_NAMESPACE_GINAC
1013 return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
1016 ex mul::smod(const numeric &xi) const
1018 #ifdef DO_GINAC_ASSERT
1019 epvector::const_iterator it = seq.begin();
1020 epvector::const_iterator itend = seq.end();
1021 while (it != itend) {
1022 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
1025 #endif // def DO_GINAC_ASSERT
1026 mul * mulcopyp=new mul(*this);
1027 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1028 #ifndef NO_NAMESPACE_GINAC
1029 mulcopyp->overall_coeff = GiNaC::smod(ex_to_numeric(overall_coeff),xi);
1030 #else // ndef NO_NAMESPACE_GINAC
1031 mulcopyp->overall_coeff = ::smod(ex_to_numeric(overall_coeff),xi);
1032 #endif // ndef NO_NAMESPACE_GINAC
1033 mulcopyp->clearflag(status_flags::evaluated);
1034 mulcopyp->clearflag(status_flags::hash_calculated);
1035 return mulcopyp->setflag(status_flags::dynallocated);
1039 /** Exception thrown by heur_gcd() to signal failure. */
1040 class gcdheu_failed {};
1042 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1043 * get_symbol_stats() must have been called previously with the input
1044 * polynomials and an iterator to the first element of the sym_desc vector
1045 * passed in. This function is used internally by gcd().
1047 * @param a first multivariate polynomial (expanded)
1048 * @param b second multivariate polynomial (expanded)
1049 * @param ca cofactor of polynomial a (returned), NULL to suppress
1050 * calculation of cofactor
1051 * @param cb cofactor of polynomial b (returned), NULL to suppress
1052 * calculation of cofactor
1053 * @param var iterator to first element of vector of sym_desc structs
1054 * @return the GCD as a new expression
1056 * @exception gcdheu_failed() */
1058 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
1060 //clog << "heur_gcd(" << a << "," << b << ")\n";
1065 // GCD of two numeric values -> CLN
1066 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1067 numeric g = gcd(ex_to_numeric(a), ex_to_numeric(b));
1072 *ca = ex_to_numeric(a).mul(rg);
1074 *cb = ex_to_numeric(b).mul(rg);
1078 // The first symbol is our main variable
1079 const symbol *x = var->sym;
1081 // Remove integer content
1082 numeric gc = gcd(a.integer_content(), b.integer_content());
1083 numeric rgc = gc.inverse();
1086 int maxdeg = max(p.degree(*x), q.degree(*x));
1088 // Find evaluation point
1089 numeric mp = p.max_coefficient(), mq = q.max_coefficient();
1092 xi = mq * _num2() + _num2();
1094 xi = mp * _num2() + _num2();
1097 for (int t=0; t<6; t++) {
1098 if (xi.int_length() * maxdeg > 100000) {
1099 //clog << "giving up heur_gcd, xi.int_length = " << xi.int_length() << ", maxdeg = " << maxdeg << endl;
1100 throw gcdheu_failed();
1103 // Apply evaluation homomorphism and calculate GCD
1104 ex gamma = heur_gcd(p.subs(*x == xi), q.subs(*x == xi), NULL, NULL, var+1).expand();
1105 if (!is_ex_exactly_of_type(gamma, fail)) {
1107 // Reconstruct polynomial from GCD of mapped polynomials
1109 numeric rxi = xi.inverse();
1110 for (int i=0; !gamma.is_zero(); i++) {
1111 ex gi = gamma.smod(xi);
1112 g += gi * power(*x, i);
1113 gamma = (gamma - gi) * rxi;
1115 // Remove integer content
1116 g /= g.integer_content();
1118 // If the calculated polynomial divides both a and b, this is the GCD
1120 if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1122 ex lc = g.lcoeff(*x);
1123 if (is_ex_exactly_of_type(lc, numeric) && ex_to_numeric(lc).is_negative())
1130 // Next evaluation point
1131 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1133 return *new ex(fail());
1137 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1140 * @param a first multivariate polynomial
1141 * @param b second multivariate polynomial
1142 * @param check_args check whether a and b are polynomials with rational
1143 * coefficients (defaults to "true")
1144 * @return the GCD as a new expression */
1146 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1148 //clog << "gcd(" << a << "," << b << ")\n";
1153 // GCD of numerics -> CLN
1154 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1155 numeric g = gcd(ex_to_numeric(a), ex_to_numeric(b));
1157 *ca = ex_to_numeric(a) / g;
1159 *cb = ex_to_numeric(b) / g;
1164 if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)) {
1165 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1168 // Partially factored cases (to avoid expanding large expressions)
1169 if (is_ex_exactly_of_type(a, mul)) {
1170 if (is_ex_exactly_of_type(b, mul) && b.nops() > a.nops())
1176 for (unsigned i=0; i<a.nops(); i++) {
1177 ex part_ca, part_cb;
1178 g *= gcd(a.op(i), part_b, &part_ca, &part_cb, check_args);
1187 } else if (is_ex_exactly_of_type(b, mul)) {
1188 if (is_ex_exactly_of_type(a, mul) && a.nops() > b.nops())
1194 for (unsigned i=0; i<b.nops(); i++) {
1195 ex part_ca, part_cb;
1196 g *= gcd(part_a, b.op(i), &part_ca, &part_cb, check_args);
1208 // Input polynomials of the form poly^n are sometimes also trivial
1209 if (is_ex_exactly_of_type(a, power)) {
1211 if (is_ex_exactly_of_type(b, power)) {
1212 if (p.is_equal(b.op(0))) {
1213 // a = p^n, b = p^m, gcd = p^min(n, m)
1214 ex exp_a = a.op(1), exp_b = b.op(1);
1215 if (exp_a < exp_b) {
1219 *cb = power(p, exp_b - exp_a);
1220 return power(p, exp_a);
1223 *ca = power(p, exp_a - exp_b);
1226 return power(p, exp_b);
1230 if (p.is_equal(b)) {
1231 // a = p^n, b = p, gcd = p
1233 *ca = power(p, a.op(1) - 1);
1239 } else if (is_ex_exactly_of_type(b, power)) {
1241 if (p.is_equal(a)) {
1242 // a = p, b = p^n, gcd = p
1246 *cb = power(p, b.op(1) - 1);
1252 // Some trivial cases
1253 ex aex = a.expand(), bex = b.expand();
1254 if (aex.is_zero()) {
1261 if (bex.is_zero()) {
1268 if (aex.is_equal(_ex1()) || bex.is_equal(_ex1())) {
1276 if (a.is_equal(b)) {
1285 // Gather symbol statistics
1286 sym_desc_vec sym_stats;
1287 get_symbol_stats(a, b, sym_stats);
1289 // The symbol with least degree is our main variable
1290 sym_desc_vec::const_iterator var = sym_stats.begin();
1291 const symbol *x = var->sym;
1293 // Cancel trivial common factor
1294 int ldeg_a = var->ldeg_a;
1295 int ldeg_b = var->ldeg_b;
1296 int min_ldeg = min(ldeg_a, ldeg_b);
1298 ex common = power(*x, min_ldeg);
1299 //clog << "trivial common factor " << common << endl;
1300 return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1303 // Try to eliminate variables
1304 if (var->deg_a == 0) {
1305 //clog << "eliminating variable " << *x << " from b" << endl;
1306 ex c = bex.content(*x);
1307 ex g = gcd(aex, c, ca, cb, false);
1309 *cb *= bex.unit(*x) * bex.primpart(*x, c);
1311 } else if (var->deg_b == 0) {
1312 //clog << "eliminating variable " << *x << " from a" << endl;
1313 ex c = aex.content(*x);
1314 ex g = gcd(c, bex, ca, cb, false);
1316 *ca *= aex.unit(*x) * aex.primpart(*x, c);
1320 // Try heuristic algorithm first, fall back to PRS if that failed
1323 g = heur_gcd(aex, bex, ca, cb, var);
1324 } catch (gcdheu_failed) {
1325 g = *new ex(fail());
1327 if (is_ex_exactly_of_type(g, fail)) {
1328 //clog << "heuristics failed" << endl;
1332 g = sr_gcd(aex, bex, x);
1333 if (g.is_equal(_ex1())) {
1334 // Keep cofactors factored if possible
1341 divide(aex, g, *ca, false);
1343 divide(bex, g, *cb, false);
1346 if (g.is_equal(_ex1())) {
1347 // Keep cofactors factored if possible
1358 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1360 * @param a first multivariate polynomial
1361 * @param b second multivariate polynomial
1362 * @param check_args check whether a and b are polynomials with rational
1363 * coefficients (defaults to "true")
1364 * @return the LCM as a new expression */
1365 ex lcm(const ex &a, const ex &b, bool check_args)
1367 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
1368 return lcm(ex_to_numeric(a), ex_to_numeric(b));
1369 if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1370 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1373 ex g = gcd(a, b, &ca, &cb, false);
1379 * Square-free factorization
1382 // Univariate GCD of polynomials in Q[x] (used internally by sqrfree()).
1383 // a and b can be multivariate polynomials but they are treated as univariate polynomials in x.
1384 static ex univariate_gcd(const ex &a, const ex &b, const symbol &x)
1390 if (a.is_equal(_ex1()) || b.is_equal(_ex1()))
1392 if (is_ex_of_type(a, numeric) && is_ex_of_type(b, numeric))
1393 return gcd(ex_to_numeric(a), ex_to_numeric(b));
1394 if (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1395 throw(std::invalid_argument("univariate_gcd: arguments must be polynomials over the rationals"));
1397 // Euclidean algorithm
1399 if (a.degree(x) >= b.degree(x)) {
1407 r = rem(c, d, x, false);
1413 return d / d.lcoeff(x);
1417 /** Compute square-free factorization of multivariate polynomial a(x) using
1420 * @param a multivariate polynomial
1421 * @param x variable to factor in
1422 * @return factored polynomial */
1423 ex sqrfree(const ex &a, const symbol &x)
1428 ex c = univariate_gcd(a, b, x);
1430 if (c.is_equal(_ex1())) {
1434 ex y = quo(b, c, x);
1435 ex z = y - w.diff(x);
1436 while (!z.is_zero()) {
1437 ex g = univariate_gcd(w, z, x);
1445 return res * power(w, i);
1450 * Normal form of rational functions
1454 * Note: The internal normal() functions (= basic::normal() and overloaded
1455 * functions) all return lists of the form {numerator, denominator}. This
1456 * is to get around mul::eval()'s automatic expansion of numeric coefficients.
1457 * E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
1458 * the information that (a+b) is the numerator and 3 is the denominator.
1461 /** Create a symbol for replacing the expression "e" (or return a previously
1462 * assigned symbol). The symbol is appended to sym_lst and returned, the
1463 * expression is appended to repl_lst.
1464 * @see ex::normal */
1465 static ex replace_with_symbol(const ex &e, lst &sym_lst, lst &repl_lst)
1467 // Expression already in repl_lst? Then return the assigned symbol
1468 for (unsigned i=0; i<repl_lst.nops(); i++)
1469 if (repl_lst.op(i).is_equal(e))
1470 return sym_lst.op(i);
1472 // Otherwise create new symbol and add to list, taking care that the
1473 // replacement expression doesn't contain symbols from the sym_lst
1474 // because subs() is not recursive
1477 ex e_replaced = e.subs(sym_lst, repl_lst);
1479 repl_lst.append(e_replaced);
1483 /** Create a symbol for replacing the expression "e" (or return a previously
1484 * assigned symbol). An expression of the form "symbol == expression" is added
1485 * to repl_lst and the symbol is returned.
1486 * @see ex::to_rational */
1487 static ex replace_with_symbol(const ex &e, lst &repl_lst)
1489 // Expression already in repl_lst? Then return the assigned symbol
1490 for (unsigned i=0; i<repl_lst.nops(); i++)
1491 if (repl_lst.op(i).op(1).is_equal(e))
1492 return repl_lst.op(i).op(0);
1494 // Otherwise create new symbol and add to list, taking care that the
1495 // replacement expression doesn't contain symbols from the sym_lst
1496 // because subs() is not recursive
1499 ex e_replaced = e.subs(repl_lst);
1500 repl_lst.append(es == e_replaced);
1504 /** Default implementation of ex::normal(). It replaces the object with a
1506 * @see ex::normal */
1507 ex basic::normal(lst &sym_lst, lst &repl_lst, int level) const
1509 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1513 /** Implementation of ex::normal() for symbols. This returns the unmodified symbol.
1514 * @see ex::normal */
1515 ex symbol::normal(lst &sym_lst, lst &repl_lst, int level) const
1517 return (new lst(*this, _ex1()))->setflag(status_flags::dynallocated);
1521 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1522 * into re+I*im and replaces I and non-rational real numbers with a temporary
1524 * @see ex::normal */
1525 ex numeric::normal(lst &sym_lst, lst &repl_lst, int level) const
1527 numeric num = numer();
1530 if (num.is_real()) {
1531 if (!num.is_integer())
1532 numex = replace_with_symbol(numex, sym_lst, repl_lst);
1534 numeric re = num.real(), im = num.imag();
1535 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, sym_lst, repl_lst);
1536 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, sym_lst, repl_lst);
1537 numex = re_ex + im_ex * replace_with_symbol(I, sym_lst, repl_lst);
1540 // Denominator is always a real integer (see numeric::denom())
1541 return (new lst(numex, denom()))->setflag(status_flags::dynallocated);
1545 /** Fraction cancellation.
1546 * @param n numerator
1547 * @param d denominator
1548 * @return cancelled fraction {n, d} as a list */
1549 static ex frac_cancel(const ex &n, const ex &d)
1553 numeric pre_factor = _num1();
1555 //clog << "frac_cancel num = " << num << ", den = " << den << endl;
1557 // Handle special cases where numerator or denominator is 0
1559 return (new lst(_ex0(), _ex1()))->setflag(status_flags::dynallocated);
1560 if (den.expand().is_zero())
1561 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
1563 // Bring numerator and denominator to Z[X] by multiplying with
1564 // LCM of all coefficients' denominators
1565 numeric num_lcm = lcm_of_coefficients_denominators(num);
1566 numeric den_lcm = lcm_of_coefficients_denominators(den);
1567 num = multiply_lcm(num, num_lcm);
1568 den = multiply_lcm(den, den_lcm);
1569 pre_factor = den_lcm / num_lcm;
1571 // Cancel GCD from numerator and denominator
1573 if (gcd(num, den, &cnum, &cden, false) != _ex1()) {
1578 // Make denominator unit normal (i.e. coefficient of first symbol
1579 // as defined by get_first_symbol() is made positive)
1581 if (get_first_symbol(den, x)) {
1582 GINAC_ASSERT(is_ex_exactly_of_type(den.unit(*x),numeric));
1583 if (ex_to_numeric(den.unit(*x)).is_negative()) {
1589 // Return result as list
1590 //clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << endl;
1591 return (new lst(num * pre_factor.numer(), den * pre_factor.denom()))->setflag(status_flags::dynallocated);
1595 /** Implementation of ex::normal() for a sum. It expands terms and performs
1596 * fractional addition.
1597 * @see ex::normal */
1598 ex add::normal(lst &sym_lst, lst &repl_lst, int level) const
1600 // Normalize and expand children, chop into summands
1602 o.reserve(seq.size()+1);
1603 epvector::const_iterator it = seq.begin(), itend = seq.end();
1604 while (it != itend) {
1606 // Normalize and expand child
1607 ex n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1).expand();
1609 // If numerator is a sum, chop into summands
1610 if (is_ex_exactly_of_type(n.op(0), add)) {
1611 epvector::const_iterator bit = ex_to_add(n.op(0)).seq.begin(), bitend = ex_to_add(n.op(0)).seq.end();
1612 while (bit != bitend) {
1613 o.push_back((new lst(recombine_pair_to_ex(*bit), n.op(1)))->setflag(status_flags::dynallocated));
1617 // The overall_coeff is already normalized (== rational), we just
1618 // split it into numerator and denominator
1619 GINAC_ASSERT(ex_to_numeric(ex_to_add(n.op(0)).overall_coeff).is_rational());
1620 numeric overall = ex_to_numeric(ex_to_add(n.op(0)).overall_coeff);
1621 o.push_back((new lst(overall.numer(), overall.denom() * n.op(1)))->setflag(status_flags::dynallocated));
1626 o.push_back(overall_coeff.bp->normal(sym_lst, repl_lst, level-1));
1628 // o is now a vector of {numerator, denominator} lists
1630 // Determine common denominator
1632 exvector::const_iterator ait = o.begin(), aitend = o.end();
1633 //clog << "add::normal uses the following summands:\n";
1634 while (ait != aitend) {
1635 //clog << " num = " << ait->op(0) << ", den = " << ait->op(1) << endl;
1636 den = lcm(ait->op(1), den, false);
1639 //clog << " common denominator = " << den << endl;
1642 if (den.is_equal(_ex1())) {
1644 // Common denominator is 1, simply add all numerators
1646 for (ait=o.begin(); ait!=aitend; ait++) {
1647 num_seq.push_back(ait->op(0));
1649 return (new lst((new add(num_seq))->setflag(status_flags::dynallocated), den))->setflag(status_flags::dynallocated);
1653 // Perform fractional addition
1655 for (ait=o.begin(); ait!=aitend; ait++) {
1657 if (!divide(den, ait->op(1), q, false)) {
1658 // should not happen
1659 throw(std::runtime_error("invalid expression in add::normal, division failed"));
1661 num_seq.push_back((ait->op(0) * q).expand());
1663 ex num = (new add(num_seq))->setflag(status_flags::dynallocated);
1665 // Cancel common factors from num/den
1666 return frac_cancel(num, den);
1671 /** Implementation of ex::normal() for a product. It cancels common factors
1673 * @see ex::normal() */
1674 ex mul::normal(lst &sym_lst, lst &repl_lst, int level) const
1676 // Normalize children, separate into numerator and denominator
1680 epvector::const_iterator it = seq.begin(), itend = seq.end();
1681 while (it != itend) {
1682 n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1);
1687 n = overall_coeff.bp->normal(sym_lst, repl_lst, level-1);
1691 // Perform fraction cancellation
1692 return frac_cancel(num, den);
1696 /** Implementation of ex::normal() for powers. It normalizes the basis,
1697 * distributes integer exponents to numerator and denominator, and replaces
1698 * non-integer powers by temporary symbols.
1699 * @see ex::normal */
1700 ex power::normal(lst &sym_lst, lst &repl_lst, int level) const
1703 ex n = basis.bp->normal(sym_lst, repl_lst, level-1);
1705 if (exponent.info(info_flags::integer)) {
1707 if (exponent.info(info_flags::positive)) {
1709 // (a/b)^n -> {a^n, b^n}
1710 return (new lst(power(n.op(0), exponent), power(n.op(1), exponent)))->setflag(status_flags::dynallocated);
1712 } else if (exponent.info(info_flags::negative)) {
1714 // (a/b)^-n -> {b^n, a^n}
1715 return (new lst(power(n.op(1), -exponent), power(n.op(0), -exponent)))->setflag(status_flags::dynallocated);
1720 if (exponent.info(info_flags::positive)) {
1722 // (a/b)^x -> {sym((a/b)^x), 1}
1723 return (new lst(replace_with_symbol(power(n.op(0) / n.op(1), exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1725 } else if (exponent.info(info_flags::negative)) {
1727 if (n.op(1).is_equal(_ex1())) {
1729 // a^-x -> {1, sym(a^x)}
1730 return (new lst(_ex1(), replace_with_symbol(power(n.op(0), -exponent), sym_lst, repl_lst)))->setflag(status_flags::dynallocated);
1734 // (a/b)^-x -> {sym((b/a)^x), 1}
1735 return (new lst(replace_with_symbol(power(n.op(1) / n.op(0), -exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1738 } else { // exponent not numeric
1740 // (a/b)^x -> {sym((a/b)^x, 1}
1741 return (new lst(replace_with_symbol(power(n.op(0) / n.op(1), exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1747 /** Implementation of ex::normal() for pseries. It normalizes each coefficient and
1748 * replaces the series by a temporary symbol.
1749 * @see ex::normal */
1750 ex pseries::normal(lst &sym_lst, lst &repl_lst, int level) const
1753 new_seq.reserve(seq.size());
1755 epvector::const_iterator it = seq.begin(), itend = seq.end();
1756 while (it != itend) {
1757 new_seq.push_back(expair(it->rest.normal(), it->coeff));
1760 ex n = pseries(relational(var,point), new_seq);
1761 return (new lst(replace_with_symbol(n, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1765 /** Normalization of rational functions.
1766 * This function converts an expression to its normal form
1767 * "numerator/denominator", where numerator and denominator are (relatively
1768 * prime) polynomials. Any subexpressions which are not rational functions
1769 * (like non-rational numbers, non-integer powers or functions like sin(),
1770 * cos() etc.) are replaced by temporary symbols which are re-substituted by
1771 * the (normalized) subexpressions before normal() returns (this way, any
1772 * expression can be treated as a rational function). normal() is applied
1773 * recursively to arguments of functions etc.
1775 * @param level maximum depth of recursion
1776 * @return normalized expression */
1777 ex ex::normal(int level) const
1779 lst sym_lst, repl_lst;
1781 ex e = bp->normal(sym_lst, repl_lst, level);
1782 GINAC_ASSERT(is_ex_of_type(e, lst));
1784 // Re-insert replaced symbols
1785 if (sym_lst.nops() > 0)
1786 e = e.subs(sym_lst, repl_lst);
1788 // Convert {numerator, denominator} form back to fraction
1789 return e.op(0) / e.op(1);
1792 /** Numerator of an expression. If the expression is not of the normal form
1793 * "numerator/denominator", it is first converted to this form and then the
1794 * numerator is returned.
1797 * @return numerator */
1798 ex ex::numer(void) const
1800 lst sym_lst, repl_lst;
1802 ex e = bp->normal(sym_lst, repl_lst, 0);
1803 GINAC_ASSERT(is_ex_of_type(e, lst));
1805 // Re-insert replaced symbols
1806 if (sym_lst.nops() > 0)
1807 return e.op(0).subs(sym_lst, repl_lst);
1812 /** Denominator of an expression. If the expression is not of the normal form
1813 * "numerator/denominator", it is first converted to this form and then the
1814 * denominator is returned.
1817 * @return denominator */
1818 ex ex::denom(void) const
1820 lst sym_lst, repl_lst;
1822 ex e = bp->normal(sym_lst, repl_lst, 0);
1823 GINAC_ASSERT(is_ex_of_type(e, lst));
1825 // Re-insert replaced symbols
1826 if (sym_lst.nops() > 0)
1827 return e.op(1).subs(sym_lst, repl_lst);
1833 /** Default implementation of ex::to_rational(). It replaces the object with a
1835 * @see ex::to_rational */
1836 ex basic::to_rational(lst &repl_lst) const
1838 return replace_with_symbol(*this, repl_lst);
1842 /** Implementation of ex::to_rational() for symbols. This returns the unmodified symbol.
1843 * @see ex::to_rational */
1844 ex symbol::to_rational(lst &repl_lst) const
1850 /** Implementation of ex::to_rational() for a numeric. It splits complex numbers
1851 * into re+I*im and replaces I and non-rational real numbers with a temporary
1853 * @see ex::to_rational */
1854 ex numeric::to_rational(lst &repl_lst) const
1856 numeric num = numer();
1859 if (num.is_real()) {
1860 if (!num.is_integer())
1861 numex = replace_with_symbol(numex, repl_lst);
1863 numeric re = num.real(), im = num.imag();
1864 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl_lst);
1865 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl_lst);
1866 numex = re_ex + im_ex * replace_with_symbol(I, repl_lst);
1872 /** Implementation of ex::to_rational() for powers. It replaces non-integer
1873 * powers by temporary symbols.
1874 * @see ex::to_rational */
1875 ex power::to_rational(lst &repl_lst) const
1877 if (exponent.info(info_flags::integer))
1878 return power(basis.to_rational(repl_lst), exponent);
1880 return replace_with_symbol(*this, repl_lst);
1884 /** Rationalization of non-rational functions.
1885 * This function converts a general expression to a rational polynomial
1886 * by replacing all non-rational subexpressions (like non-rational numbers,
1887 * non-integer powers or functions like sin(), cos() etc.) to temporary
1888 * symbols. This makes it possible to use functions like gcd() and divide()
1889 * on non-rational functions by applying to_rational() on the arguments,
1890 * calling the desired function and re-substituting the temporary symbols
1891 * in the result. To make the last step possible, all temporary symbols and
1892 * their associated expressions are collected in the list specified by the
1893 * repl_lst parameter in the form {symbol == expression}, ready to be passed
1894 * as an argument to ex::subs().
1896 * @param repl_lst collects a list of all temporary symbols and their replacements
1897 * @return rationalized expression */
1898 ex ex::to_rational(lst &repl_lst) const
1900 return bp->to_rational(repl_lst);
1904 #ifndef NO_NAMESPACE_GINAC
1905 } // namespace GiNaC
1906 #endif // ndef NO_NAMESPACE_GINAC