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.
10 * GiNaC Copyright (C) 1999-2000 Johannes Gutenberg University Mainz, Germany
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
36 #include "expairseq.h"
45 #include "relational.h"
50 #ifndef NO_NAMESPACE_GINAC
52 #endif // ndef NO_NAMESPACE_GINAC
54 // If comparing expressions (ex::compare()) is fast, you can set this to 1.
55 // Some routines like quo(), rem() and gcd() will then return a quick answer
56 // when they are called with two identical arguments.
57 #define FAST_COMPARE 1
59 // Set this if you want divide_in_z() to use remembering
60 #define USE_REMEMBER 0
62 // Set this if you want divide_in_z() to use trial division followed by
63 // polynomial interpolation (usually slower except for very large problems)
64 #define USE_TRIAL_DIVISION 0
66 // Set this to enable some statistical output for the GCD routines
71 // Statistics variables
72 static int gcd_called = 0;
73 static int sr_gcd_called = 0;
74 static int heur_gcd_called = 0;
75 static int heur_gcd_failed = 0;
77 // Print statistics at end of program
78 static struct _stat_print {
81 cout << "gcd() called " << gcd_called << " times\n";
82 cout << "sr_gcd() called " << sr_gcd_called << " times\n";
83 cout << "heur_gcd() called " << heur_gcd_called << " times\n";
84 cout << "heur_gcd() failed " << heur_gcd_failed << " times\n";
90 /** Return pointer to first symbol found in expression. Due to GiNaCĀ“s
91 * internal ordering of terms, it may not be obvious which symbol this
92 * function returns for a given expression.
94 * @param e expression to search
95 * @param x pointer to first symbol found (returned)
96 * @return "false" if no symbol was found, "true" otherwise */
98 static bool get_first_symbol(const ex &e, const symbol *&x)
100 if (is_ex_exactly_of_type(e, symbol)) {
101 x = static_cast<symbol *>(e.bp);
103 } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
104 for (unsigned i=0; i<e.nops(); i++)
105 if (get_first_symbol(e.op(i), x))
107 } else if (is_ex_exactly_of_type(e, power)) {
108 if (get_first_symbol(e.op(0), x))
116 * Statistical information about symbols in polynomials
119 /** This structure holds information about the highest and lowest degrees
120 * in which a symbol appears in two multivariate polynomials "a" and "b".
121 * A vector of these structures with information about all symbols in
122 * two polynomials can be created with the function get_symbol_stats().
124 * @see get_symbol_stats */
126 /** Pointer to symbol */
129 /** Highest degree of symbol in polynomial "a" */
132 /** Highest degree of symbol in polynomial "b" */
135 /** Lowest degree of symbol in polynomial "a" */
138 /** Lowest degree of symbol in polynomial "b" */
141 /** Minimum of ldeg_a and ldeg_b (Used for sorting) */
144 /** Commparison operator for sorting */
145 bool operator<(const sym_desc &x) const {return min_deg < x.min_deg;}
148 // Vector of sym_desc structures
149 typedef vector<sym_desc> sym_desc_vec;
151 // Add symbol the sym_desc_vec (used internally by get_symbol_stats())
152 static void add_symbol(const symbol *s, sym_desc_vec &v)
154 sym_desc_vec::iterator it = v.begin(), itend = v.end();
155 while (it != itend) {
156 if (it->sym->compare(*s) == 0) // If it's already in there, don't add it a second time
165 // Collect all symbols of an expression (used internally by get_symbol_stats())
166 static void collect_symbols(const ex &e, sym_desc_vec &v)
168 if (is_ex_exactly_of_type(e, symbol)) {
169 add_symbol(static_cast<symbol *>(e.bp), v);
170 } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
171 for (unsigned i=0; i<e.nops(); i++)
172 collect_symbols(e.op(i), v);
173 } else if (is_ex_exactly_of_type(e, power)) {
174 collect_symbols(e.op(0), v);
178 /** Collect statistical information about symbols in polynomials.
179 * This function fills in a vector of "sym_desc" structs which contain
180 * information about the highest and lowest degrees of all symbols that
181 * appear in two polynomials. The vector is then sorted by minimum
182 * degree (lowest to highest). The information gathered by this
183 * function is used by the GCD routines to identify trivial factors
184 * and to determine which variable to choose as the main variable
185 * for GCD computation.
187 * @param a first multivariate polynomial
188 * @param b second multivariate polynomial
189 * @param v vector of sym_desc structs (filled in) */
191 static void get_symbol_stats(const ex &a, const ex &b, sym_desc_vec &v)
193 collect_symbols(a.eval(), v); // eval() to expand assigned symbols
194 collect_symbols(b.eval(), v);
195 sym_desc_vec::iterator it = v.begin(), itend = v.end();
196 while (it != itend) {
197 int deg_a = a.degree(*(it->sym));
198 int deg_b = b.degree(*(it->sym));
201 it->min_deg = min(deg_a, deg_b);
202 it->ldeg_a = a.ldegree(*(it->sym));
203 it->ldeg_b = b.ldegree(*(it->sym));
206 sort(v.begin(), v.end());
211 * Computation of LCM of denominators of coefficients of a polynomial
214 // Compute LCM of denominators of coefficients by going through the
215 // expression recursively (used internally by lcm_of_coefficients_denominators())
216 static numeric lcmcoeff(const ex &e, const numeric &l)
218 if (e.info(info_flags::rational))
219 return lcm(ex_to_numeric(e).denom(), l);
220 else if (is_ex_exactly_of_type(e, add)) {
222 for (unsigned i=0; i<e.nops(); i++)
223 c = lcmcoeff(e.op(i), c);
225 } else if (is_ex_exactly_of_type(e, mul)) {
227 for (unsigned i=0; i<e.nops(); i++)
228 c *= lcmcoeff(e.op(i), _num1());
230 } else if (is_ex_exactly_of_type(e, power))
231 return pow(lcmcoeff(e.op(0), l), ex_to_numeric(e.op(1)));
235 /** Compute LCM of denominators of coefficients of a polynomial.
236 * Given a polynomial with rational coefficients, this function computes
237 * the LCM of the denominators of all coefficients. This can be used
238 * to bring a polynomial from Q[X] to Z[X].
240 * @param e multivariate polynomial (need not be expanded)
241 * @return LCM of denominators of coefficients */
243 static numeric lcm_of_coefficients_denominators(const ex &e)
245 return lcmcoeff(e, _num1());
248 /** Bring polynomial from Q[X] to Z[X] by multiplying in the previously
249 * determined LCM of the coefficient's denominators.
251 * @param e multivariate polynomial (need not be expanded)
252 * @param lcm LCM to multiply in */
254 static ex multiply_lcm(const ex &e, const numeric &lcm)
256 if (is_ex_exactly_of_type(e, mul)) {
258 numeric lcm_accum = _num1();
259 for (unsigned i=0; i<e.nops(); i++) {
260 numeric op_lcm = lcmcoeff(e.op(i), _num1());
261 c *= multiply_lcm(e.op(i), op_lcm);
264 c *= lcm / lcm_accum;
266 } else if (is_ex_exactly_of_type(e, add)) {
268 for (unsigned i=0; i<e.nops(); i++)
269 c += multiply_lcm(e.op(i), lcm);
271 } else if (is_ex_exactly_of_type(e, power)) {
272 return pow(multiply_lcm(e.op(0), lcm.power(ex_to_numeric(e.op(1)).inverse())), e.op(1));
278 /** Compute the integer content (= GCD of all numeric coefficients) of an
279 * expanded polynomial.
281 * @param e expanded polynomial
282 * @return integer content */
284 numeric ex::integer_content(void) const
287 return bp->integer_content();
290 numeric basic::integer_content(void) const
295 numeric numeric::integer_content(void) const
300 numeric add::integer_content(void) const
302 epvector::const_iterator it = seq.begin();
303 epvector::const_iterator itend = seq.end();
305 while (it != itend) {
306 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
307 GINAC_ASSERT(is_ex_exactly_of_type(it->coeff,numeric));
308 c = gcd(ex_to_numeric(it->coeff), c);
311 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
312 c = gcd(ex_to_numeric(overall_coeff),c);
316 numeric mul::integer_content(void) const
318 #ifdef DO_GINAC_ASSERT
319 epvector::const_iterator it = seq.begin();
320 epvector::const_iterator itend = seq.end();
321 while (it != itend) {
322 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
325 #endif // def DO_GINAC_ASSERT
326 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
327 return abs(ex_to_numeric(overall_coeff));
332 * Polynomial quotients and remainders
335 /** Quotient q(x) of polynomials a(x) and b(x) in Q[x].
336 * It satisfies a(x)=b(x)*q(x)+r(x).
338 * @param a first polynomial in x (dividend)
339 * @param b second polynomial in x (divisor)
340 * @param x a and b are polynomials in x
341 * @param check_args check whether a and b are polynomials with rational
342 * coefficients (defaults to "true")
343 * @return quotient of a and b in Q[x] */
345 ex quo(const ex &a, const ex &b, const symbol &x, bool check_args)
348 throw(std::overflow_error("quo: division by zero"));
349 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
355 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
356 throw(std::invalid_argument("quo: arguments must be polynomials over the rationals"));
358 // Polynomial long division
363 int bdeg = b.degree(x);
364 int rdeg = r.degree(x);
365 ex blcoeff = b.expand().coeff(x, bdeg);
366 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
367 while (rdeg >= bdeg) {
368 ex term, rcoeff = r.coeff(x, rdeg);
369 if (blcoeff_is_numeric)
370 term = rcoeff / blcoeff;
372 if (!divide(rcoeff, blcoeff, term, false))
373 return *new ex(fail());
375 term *= power(x, rdeg - bdeg);
377 r -= (term * b).expand();
386 /** Remainder r(x) of polynomials a(x) and b(x) in Q[x].
387 * It satisfies a(x)=b(x)*q(x)+r(x).
389 * @param a first polynomial in x (dividend)
390 * @param b second polynomial in x (divisor)
391 * @param x a and b are polynomials in x
392 * @param check_args check whether a and b are polynomials with rational
393 * coefficients (defaults to "true")
394 * @return remainder of a(x) and b(x) in Q[x] */
396 ex rem(const ex &a, const ex &b, const symbol &x, bool check_args)
399 throw(std::overflow_error("rem: division by zero"));
400 if (is_ex_exactly_of_type(a, numeric)) {
401 if (is_ex_exactly_of_type(b, numeric))
410 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
411 throw(std::invalid_argument("rem: arguments must be polynomials over the rationals"));
413 // Polynomial long division
417 int bdeg = b.degree(x);
418 int rdeg = r.degree(x);
419 ex blcoeff = b.expand().coeff(x, bdeg);
420 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
421 while (rdeg >= bdeg) {
422 ex term, rcoeff = r.coeff(x, rdeg);
423 if (blcoeff_is_numeric)
424 term = rcoeff / blcoeff;
426 if (!divide(rcoeff, blcoeff, term, false))
427 return *new ex(fail());
429 term *= power(x, rdeg - bdeg);
430 r -= (term * b).expand();
439 /** Pseudo-remainder of polynomials a(x) and b(x) in Z[x].
441 * @param a first polynomial in x (dividend)
442 * @param b second polynomial in x (divisor)
443 * @param x a and b are polynomials in x
444 * @param check_args check whether a and b are polynomials with rational
445 * coefficients (defaults to "true")
446 * @return pseudo-remainder of a(x) and b(x) in Z[x] */
448 ex prem(const ex &a, const ex &b, const symbol &x, bool check_args)
451 throw(std::overflow_error("prem: division by zero"));
452 if (is_ex_exactly_of_type(a, numeric)) {
453 if (is_ex_exactly_of_type(b, numeric))
458 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
459 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
461 // Polynomial long division
464 int rdeg = r.degree(x);
465 int bdeg = eb.degree(x);
468 blcoeff = eb.coeff(x, bdeg);
472 eb -= blcoeff * power(x, bdeg);
476 int delta = rdeg - bdeg + 1, i = 0;
477 while (rdeg >= bdeg && !r.is_zero()) {
478 ex rlcoeff = r.coeff(x, rdeg);
479 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
483 r -= rlcoeff * power(x, rdeg);
484 r = (blcoeff * r).expand() - term;
488 return power(blcoeff, delta - i) * r;
492 /** Exact polynomial division of a(X) by b(X) in Q[X].
494 * @param a first multivariate polynomial (dividend)
495 * @param b second multivariate polynomial (divisor)
496 * @param q quotient (returned)
497 * @param check_args check whether a and b are polynomials with rational
498 * coefficients (defaults to "true")
499 * @return "true" when exact division succeeds (quotient returned in q),
500 * "false" otherwise */
502 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
506 throw(std::overflow_error("divide: division by zero"));
507 if (is_ex_exactly_of_type(b, numeric)) {
510 } else if (is_ex_exactly_of_type(a, numeric))
518 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
519 throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
523 if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
524 throw(std::invalid_argument("invalid expression in divide()"));
526 // Polynomial long division (recursive)
530 int bdeg = b.degree(*x);
531 int rdeg = r.degree(*x);
532 ex blcoeff = b.expand().coeff(*x, bdeg);
533 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
534 while (rdeg >= bdeg) {
535 ex term, rcoeff = r.coeff(*x, rdeg);
536 if (blcoeff_is_numeric)
537 term = rcoeff / blcoeff;
539 if (!divide(rcoeff, blcoeff, term, false))
541 term *= power(*x, rdeg - bdeg);
543 r -= (term * b).expand();
557 typedef pair<ex, ex> ex2;
558 typedef pair<ex, bool> exbool;
561 bool operator() (const ex2 p, const ex2 q) const
563 return p.first.compare(q.first) < 0 || (!(q.first.compare(p.first) < 0) && p.second.compare(q.second) < 0);
567 typedef map<ex2, exbool, ex2_less> ex2_exbool_remember;
571 /** Exact polynomial division of a(X) by b(X) in Z[X].
572 * This functions works like divide() but the input and output polynomials are
573 * in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
574 * divide(), it doesnĀ“t check whether the input polynomials really are integer
575 * polynomials, so be careful of what you pass in. Also, you have to run
576 * get_symbol_stats() over the input polynomials before calling this function
577 * and pass an iterator to the first element of the sym_desc vector. This
578 * function is used internally by the heur_gcd().
580 * @param a first multivariate polynomial (dividend)
581 * @param b second multivariate polynomial (divisor)
582 * @param q quotient (returned)
583 * @param var iterator to first element of vector of sym_desc structs
584 * @return "true" when exact division succeeds (the quotient is returned in
585 * q), "false" otherwise.
586 * @see get_symbol_stats, heur_gcd */
587 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
591 throw(std::overflow_error("divide_in_z: division by zero"));
592 if (b.is_equal(_ex1())) {
596 if (is_ex_exactly_of_type(a, numeric)) {
597 if (is_ex_exactly_of_type(b, numeric)) {
599 return q.info(info_flags::integer);
612 static ex2_exbool_remember dr_remember;
613 ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
614 if (remembered != dr_remember.end()) {
615 q = remembered->second.first;
616 return remembered->second.second;
621 const symbol *x = var->sym;
624 int adeg = a.degree(*x), bdeg = b.degree(*x);
628 #if USE_TRIAL_DIVISION
630 // Trial division with polynomial interpolation
633 // Compute values at evaluation points 0..adeg
634 vector<numeric> alpha; alpha.reserve(adeg + 1);
635 exvector u; u.reserve(adeg + 1);
636 numeric point = _num0();
638 for (i=0; i<=adeg; i++) {
639 ex bs = b.subs(*x == point);
640 while (bs.is_zero()) {
642 bs = b.subs(*x == point);
644 if (!divide_in_z(a.subs(*x == point), bs, c, var+1))
646 alpha.push_back(point);
652 vector<numeric> rcp; rcp.reserve(adeg + 1);
653 rcp.push_back(_num0());
654 for (k=1; k<=adeg; k++) {
655 numeric product = alpha[k] - alpha[0];
657 product *= alpha[k] - alpha[i];
658 rcp.push_back(product.inverse());
661 // Compute Newton coefficients
662 exvector v; v.reserve(adeg + 1);
664 for (k=1; k<=adeg; k++) {
666 for (i=k-2; i>=0; i--)
667 temp = temp * (alpha[k] - alpha[i]) + v[i];
668 v.push_back((u[k] - temp) * rcp[k]);
671 // Convert from Newton form to standard form
673 for (k=adeg-1; k>=0; k--)
674 c = c * (*x - alpha[k]) + v[k];
676 if (c.degree(*x) == (adeg - bdeg)) {
684 // Polynomial long division (recursive)
690 ex blcoeff = eb.coeff(*x, bdeg);
691 while (rdeg >= bdeg) {
692 ex term, rcoeff = r.coeff(*x, rdeg);
693 if (!divide_in_z(rcoeff, blcoeff, term, var+1))
695 term = (term * power(*x, rdeg - bdeg)).expand();
697 r -= (term * eb).expand();
700 dr_remember[ex2(a, b)] = exbool(q, true);
707 dr_remember[ex2(a, b)] = exbool(q, false);
716 * Separation of unit part, content part and primitive part of polynomials
719 /** Compute unit part (= sign of leading coefficient) of a multivariate
720 * polynomial in Z[x]. The product of unit part, content part, and primitive
721 * part is the polynomial itself.
723 * @param x variable in which to compute the unit part
725 * @see ex::content, ex::primpart */
726 ex ex::unit(const symbol &x) const
728 ex c = expand().lcoeff(x);
729 if (is_ex_exactly_of_type(c, numeric))
730 return c < _ex0() ? _ex_1() : _ex1();
733 if (get_first_symbol(c, y))
736 throw(std::invalid_argument("invalid expression in unit()"));
741 /** Compute content part (= unit normal GCD of all coefficients) of a
742 * multivariate polynomial in Z[x]. The product of unit part, content part,
743 * and primitive part is the polynomial itself.
745 * @param x variable in which to compute the content part
746 * @return content part
747 * @see ex::unit, ex::primpart */
748 ex ex::content(const symbol &x) const
752 if (is_ex_exactly_of_type(*this, numeric))
753 return info(info_flags::negative) ? -*this : *this;
758 // First, try the integer content
759 ex c = e.integer_content();
761 ex lcoeff = r.lcoeff(x);
762 if (lcoeff.info(info_flags::integer))
765 // GCD of all coefficients
766 int deg = e.degree(x);
767 int ldeg = e.ldegree(x);
769 return e.lcoeff(x) / e.unit(x);
771 for (int i=ldeg; i<=deg; i++)
772 c = gcd(e.coeff(x, i), c, NULL, NULL, false);
777 /** Compute primitive part of a multivariate polynomial in Z[x].
778 * The product of unit part, content part, and primitive part is the
781 * @param x variable in which to compute the primitive part
782 * @return primitive part
783 * @see ex::unit, ex::content */
784 ex ex::primpart(const symbol &x) const
788 if (is_ex_exactly_of_type(*this, numeric))
795 if (is_ex_exactly_of_type(c, numeric))
796 return *this / (c * u);
798 return quo(*this, c * u, x, false);
802 /** Compute primitive part of a multivariate polynomial in Z[x] when the
803 * content part is already known. This function is faster in computing the
804 * primitive part than the previous function.
806 * @param x variable in which to compute the primitive part
807 * @param c previously computed content part
808 * @return primitive part */
810 ex ex::primpart(const symbol &x, const ex &c) const
816 if (is_ex_exactly_of_type(*this, numeric))
820 if (is_ex_exactly_of_type(c, numeric))
821 return *this / (c * u);
823 return quo(*this, c * u, x, false);
828 * GCD of multivariate polynomials
831 /** Compute GCD of multivariate polynomials using the subresultant PRS
832 * algorithm. This function is used internally gy gcd().
834 * @param a first multivariate polynomial
835 * @param b second multivariate polynomial
836 * @param x pointer to symbol (main variable) in which to compute the GCD in
837 * @return the GCD as a new expression
840 static ex sr_gcd(const ex &a, const ex &b, const symbol *x)
842 //clog << "sr_gcd(" << a << "," << b << ")\n";
847 // Sort c and d so that c has higher degree
849 int adeg = a.degree(*x), bdeg = b.degree(*x);
863 // Remove content from c and d, to be attached to GCD later
864 ex cont_c = c.content(*x);
865 ex cont_d = d.content(*x);
866 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
869 c = c.primpart(*x, cont_c);
870 d = d.primpart(*x, cont_d);
871 //clog << " content " << gamma << " removed, continuing with sr_gcd(" << c << "," << d << ")\n";
873 // First element of subresultant sequence
874 ex r = _ex0(), ri = _ex1(), psi = _ex1();
875 int delta = cdeg - ddeg;
878 // Calculate polynomial pseudo-remainder
879 //clog << " start of loop, psi = " << psi << ", calculating pseudo-remainder...\n";
880 r = prem(c, d, *x, false);
882 return gamma * d.primpart(*x);
885 //clog << " dividing...\n";
886 if (!divide(r, ri * power(psi, delta), d, false))
887 throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
890 if (is_ex_exactly_of_type(r, numeric))
893 return gamma * r.primpart(*x);
896 // Next element of subresultant sequence
897 //clog << " calculating next subresultant...\n";
898 ri = c.expand().lcoeff(*x);
902 divide(power(ri, delta), power(psi, delta-1), psi, false);
908 /** Return maximum (absolute value) coefficient of a polynomial.
909 * This function is used internally by heur_gcd().
911 * @param e expanded multivariate polynomial
912 * @return maximum coefficient
915 numeric ex::max_coefficient(void) const
918 return bp->max_coefficient();
921 numeric basic::max_coefficient(void) const
926 numeric numeric::max_coefficient(void) const
931 numeric add::max_coefficient(void) const
933 epvector::const_iterator it = seq.begin();
934 epvector::const_iterator itend = seq.end();
935 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
936 numeric cur_max = abs(ex_to_numeric(overall_coeff));
937 while (it != itend) {
939 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
940 a = abs(ex_to_numeric(it->coeff));
948 numeric mul::max_coefficient(void) const
950 #ifdef DO_GINAC_ASSERT
951 epvector::const_iterator it = seq.begin();
952 epvector::const_iterator itend = seq.end();
953 while (it != itend) {
954 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
957 #endif // def DO_GINAC_ASSERT
958 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
959 return abs(ex_to_numeric(overall_coeff));
963 /** Apply symmetric modular homomorphism to a multivariate polynomial.
964 * This function is used internally by heur_gcd().
966 * @param e expanded multivariate polynomial
968 * @return mapped polynomial
971 ex ex::smod(const numeric &xi) const
977 ex basic::smod(const numeric &xi) const
982 ex numeric::smod(const numeric &xi) const
984 #ifndef NO_NAMESPACE_GINAC
985 return GiNaC::smod(*this, xi);
986 #else // ndef NO_NAMESPACE_GINAC
987 return ::smod(*this, xi);
988 #endif // ndef NO_NAMESPACE_GINAC
991 ex add::smod(const numeric &xi) const
994 newseq.reserve(seq.size()+1);
995 epvector::const_iterator it = seq.begin();
996 epvector::const_iterator itend = seq.end();
997 while (it != itend) {
998 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
999 #ifndef NO_NAMESPACE_GINAC
1000 numeric coeff = GiNaC::smod(ex_to_numeric(it->coeff), xi);
1001 #else // ndef NO_NAMESPACE_GINAC
1002 numeric coeff = ::smod(ex_to_numeric(it->coeff), xi);
1003 #endif // ndef NO_NAMESPACE_GINAC
1004 if (!coeff.is_zero())
1005 newseq.push_back(expair(it->rest, coeff));
1008 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1009 #ifndef NO_NAMESPACE_GINAC
1010 numeric coeff = GiNaC::smod(ex_to_numeric(overall_coeff), xi);
1011 #else // ndef NO_NAMESPACE_GINAC
1012 numeric coeff = ::smod(ex_to_numeric(overall_coeff), xi);
1013 #endif // ndef NO_NAMESPACE_GINAC
1014 return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
1017 ex mul::smod(const numeric &xi) const
1019 #ifdef DO_GINAC_ASSERT
1020 epvector::const_iterator it = seq.begin();
1021 epvector::const_iterator itend = seq.end();
1022 while (it != itend) {
1023 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
1026 #endif // def DO_GINAC_ASSERT
1027 mul * mulcopyp=new mul(*this);
1028 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1029 #ifndef NO_NAMESPACE_GINAC
1030 mulcopyp->overall_coeff = GiNaC::smod(ex_to_numeric(overall_coeff),xi);
1031 #else // ndef NO_NAMESPACE_GINAC
1032 mulcopyp->overall_coeff = ::smod(ex_to_numeric(overall_coeff),xi);
1033 #endif // ndef NO_NAMESPACE_GINAC
1034 mulcopyp->clearflag(status_flags::evaluated);
1035 mulcopyp->clearflag(status_flags::hash_calculated);
1036 return mulcopyp->setflag(status_flags::dynallocated);
1040 /** Exception thrown by heur_gcd() to signal failure. */
1041 class gcdheu_failed {};
1043 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1044 * get_symbol_stats() must have been called previously with the input
1045 * polynomials and an iterator to the first element of the sym_desc vector
1046 * passed in. This function is used internally by gcd().
1048 * @param a first multivariate polynomial (expanded)
1049 * @param b second multivariate polynomial (expanded)
1050 * @param ca cofactor of polynomial a (returned), NULL to suppress
1051 * calculation of cofactor
1052 * @param cb cofactor of polynomial b (returned), NULL to suppress
1053 * calculation of cofactor
1054 * @param var iterator to first element of vector of sym_desc structs
1055 * @return the GCD as a new expression
1057 * @exception gcdheu_failed() */
1059 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
1061 //clog << "heur_gcd(" << a << "," << b << ")\n";
1066 // GCD of two numeric values -> CLN
1067 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1068 numeric g = gcd(ex_to_numeric(a), ex_to_numeric(b));
1073 *ca = ex_to_numeric(a).mul(rg);
1075 *cb = ex_to_numeric(b).mul(rg);
1079 // The first symbol is our main variable
1080 const symbol *x = var->sym;
1082 // Remove integer content
1083 numeric gc = gcd(a.integer_content(), b.integer_content());
1084 numeric rgc = gc.inverse();
1087 int maxdeg = max(p.degree(*x), q.degree(*x));
1089 // Find evaluation point
1090 numeric mp = p.max_coefficient(), mq = q.max_coefficient();
1093 xi = mq * _num2() + _num2();
1095 xi = mp * _num2() + _num2();
1098 for (int t=0; t<6; t++) {
1099 if (xi.int_length() * maxdeg > 100000) {
1100 //clog << "giving up heur_gcd, xi.int_length = " << xi.int_length() << ", maxdeg = " << maxdeg << endl;
1101 throw gcdheu_failed();
1104 // Apply evaluation homomorphism and calculate GCD
1105 ex gamma = heur_gcd(p.subs(*x == xi), q.subs(*x == xi), NULL, NULL, var+1).expand();
1106 if (!is_ex_exactly_of_type(gamma, fail)) {
1108 // Reconstruct polynomial from GCD of mapped polynomials
1110 numeric rxi = xi.inverse();
1111 for (int i=0; !gamma.is_zero(); i++) {
1112 ex gi = gamma.smod(xi);
1113 g += gi * power(*x, i);
1114 gamma = (gamma - gi) * rxi;
1116 // Remove integer content
1117 g /= g.integer_content();
1119 // If the calculated polynomial divides both a and b, this is the GCD
1121 if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1123 ex lc = g.lcoeff(*x);
1124 if (is_ex_exactly_of_type(lc, numeric) && ex_to_numeric(lc).is_negative())
1131 // Next evaluation point
1132 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1134 return *new ex(fail());
1138 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1141 * @param a first multivariate polynomial
1142 * @param b second multivariate polynomial
1143 * @param check_args check whether a and b are polynomials with rational
1144 * coefficients (defaults to "true")
1145 * @return the GCD as a new expression */
1147 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1149 //clog << "gcd(" << a << "," << b << ")\n";
1154 // GCD of numerics -> CLN
1155 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1156 numeric g = gcd(ex_to_numeric(a), ex_to_numeric(b));
1158 *ca = ex_to_numeric(a) / g;
1160 *cb = ex_to_numeric(b) / g;
1165 if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)) {
1166 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1169 // Partially factored cases (to avoid expanding large expressions)
1170 if (is_ex_exactly_of_type(a, mul)) {
1171 if (is_ex_exactly_of_type(b, mul) && b.nops() > a.nops())
1177 for (unsigned i=0; i<a.nops(); i++) {
1178 ex part_ca, part_cb;
1179 g *= gcd(a.op(i), part_b, &part_ca, &part_cb, check_args);
1188 } else if (is_ex_exactly_of_type(b, mul)) {
1189 if (is_ex_exactly_of_type(a, mul) && a.nops() > b.nops())
1195 for (unsigned i=0; i<b.nops(); i++) {
1196 ex part_ca, part_cb;
1197 g *= gcd(part_a, b.op(i), &part_ca, &part_cb, check_args);
1209 // Input polynomials of the form poly^n are sometimes also trivial
1210 if (is_ex_exactly_of_type(a, power)) {
1212 if (is_ex_exactly_of_type(b, power)) {
1213 if (p.is_equal(b.op(0))) {
1214 // a = p^n, b = p^m, gcd = p^min(n, m)
1215 ex exp_a = a.op(1), exp_b = b.op(1);
1216 if (exp_a < exp_b) {
1220 *cb = power(p, exp_b - exp_a);
1221 return power(p, exp_a);
1224 *ca = power(p, exp_a - exp_b);
1227 return power(p, exp_b);
1231 if (p.is_equal(b)) {
1232 // a = p^n, b = p, gcd = p
1234 *ca = power(p, a.op(1) - 1);
1240 } else if (is_ex_exactly_of_type(b, power)) {
1242 if (p.is_equal(a)) {
1243 // a = p, b = p^n, gcd = p
1247 *cb = power(p, b.op(1) - 1);
1253 // Some trivial cases
1254 ex aex = a.expand(), bex = b.expand();
1255 if (aex.is_zero()) {
1262 if (bex.is_zero()) {
1269 if (aex.is_equal(_ex1()) || bex.is_equal(_ex1())) {
1277 if (a.is_equal(b)) {
1286 // Gather symbol statistics
1287 sym_desc_vec sym_stats;
1288 get_symbol_stats(a, b, sym_stats);
1290 // The symbol with least degree is our main variable
1291 sym_desc_vec::const_iterator var = sym_stats.begin();
1292 const symbol *x = var->sym;
1294 // Cancel trivial common factor
1295 int ldeg_a = var->ldeg_a;
1296 int ldeg_b = var->ldeg_b;
1297 int min_ldeg = min(ldeg_a, ldeg_b);
1299 ex common = power(*x, min_ldeg);
1300 //clog << "trivial common factor " << common << endl;
1301 return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1304 // Try to eliminate variables
1305 if (var->deg_a == 0) {
1306 //clog << "eliminating variable " << *x << " from b" << endl;
1307 ex c = bex.content(*x);
1308 ex g = gcd(aex, c, ca, cb, false);
1310 *cb *= bex.unit(*x) * bex.primpart(*x, c);
1312 } else if (var->deg_b == 0) {
1313 //clog << "eliminating variable " << *x << " from a" << endl;
1314 ex c = aex.content(*x);
1315 ex g = gcd(c, bex, ca, cb, false);
1317 *ca *= aex.unit(*x) * aex.primpart(*x, c);
1321 // Try heuristic algorithm first, fall back to PRS if that failed
1324 g = heur_gcd(aex, bex, ca, cb, var);
1325 } catch (gcdheu_failed) {
1326 g = *new ex(fail());
1328 if (is_ex_exactly_of_type(g, fail)) {
1329 //clog << "heuristics failed" << endl;
1333 g = sr_gcd(aex, bex, x);
1334 if (g.is_equal(_ex1())) {
1335 // Keep cofactors factored if possible
1342 divide(aex, g, *ca, false);
1344 divide(bex, g, *cb, false);
1347 if (g.is_equal(_ex1())) {
1348 // Keep cofactors factored if possible
1359 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1361 * @param a first multivariate polynomial
1362 * @param b second multivariate polynomial
1363 * @param check_args check whether a and b are polynomials with rational
1364 * coefficients (defaults to "true")
1365 * @return the LCM as a new expression */
1366 ex lcm(const ex &a, const ex &b, bool check_args)
1368 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
1369 return lcm(ex_to_numeric(a), ex_to_numeric(b));
1370 if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1371 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1374 ex g = gcd(a, b, &ca, &cb, false);
1380 * Square-free factorization
1383 // Univariate GCD of polynomials in Q[x] (used internally by sqrfree()).
1384 // a and b can be multivariate polynomials but they are treated as univariate polynomials in x.
1385 static ex univariate_gcd(const ex &a, const ex &b, const symbol &x)
1391 if (a.is_equal(_ex1()) || b.is_equal(_ex1()))
1393 if (is_ex_of_type(a, numeric) && is_ex_of_type(b, numeric))
1394 return gcd(ex_to_numeric(a), ex_to_numeric(b));
1395 if (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1396 throw(std::invalid_argument("univariate_gcd: arguments must be polynomials over the rationals"));
1398 // Euclidean algorithm
1400 if (a.degree(x) >= b.degree(x)) {
1408 r = rem(c, d, x, false);
1414 return d / d.lcoeff(x);
1418 /** Compute square-free factorization of multivariate polynomial a(x) using
1421 * @param a multivariate polynomial
1422 * @param x variable to factor in
1423 * @return factored polynomial */
1424 ex sqrfree(const ex &a, const symbol &x)
1429 ex c = univariate_gcd(a, b, x);
1431 if (c.is_equal(_ex1())) {
1435 ex y = quo(b, c, x);
1436 ex z = y - w.diff(x);
1437 while (!z.is_zero()) {
1438 ex g = univariate_gcd(w, z, x);
1446 return res * power(w, i);
1451 * Normal form of rational functions
1455 * Note: The internal normal() functions (= basic::normal() and overloaded
1456 * functions) all return lists of the form {numerator, denominator}. This
1457 * is to get around mul::eval()'s automatic expansion of numeric coefficients.
1458 * E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
1459 * the information that (a+b) is the numerator and 3 is the denominator.
1462 /** Create a symbol for replacing the expression "e" (or return a previously
1463 * assigned symbol). The symbol is appended to sym_list and returned, the
1464 * expression is appended to repl_list.
1465 * @see ex::normal */
1466 static ex replace_with_symbol(const ex &e, lst &sym_lst, lst &repl_lst)
1468 // Expression already in repl_lst? Then return the assigned symbol
1469 for (unsigned i=0; i<repl_lst.nops(); i++)
1470 if (repl_lst.op(i).is_equal(e))
1471 return sym_lst.op(i);
1473 // Otherwise create new symbol and add to list, taking care that the
1474 // replacement expression doesn't contain symbols from the sym_lst
1475 // because subs() is not recursive
1478 ex e_replaced = e.subs(sym_lst, repl_lst);
1480 repl_lst.append(e_replaced);
1485 /** Default implementation of ex::normal(). It replaces the object with a
1487 * @see ex::normal */
1488 ex basic::normal(lst &sym_lst, lst &repl_lst, int level) const
1490 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1494 /** Implementation of ex::normal() for symbols. This returns the unmodified symbol.
1495 * @see ex::normal */
1496 ex symbol::normal(lst &sym_lst, lst &repl_lst, int level) const
1498 return (new lst(*this, _ex1()))->setflag(status_flags::dynallocated);
1502 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1503 * into re+I*im and replaces I and non-rational real numbers with a temporary
1505 * @see ex::normal */
1506 ex numeric::normal(lst &sym_lst, lst &repl_lst, int level) const
1508 numeric num = numer();
1511 if (num.is_real()) {
1512 if (!num.is_integer())
1513 numex = replace_with_symbol(numex, sym_lst, repl_lst);
1515 numeric re = num.real(), im = num.imag();
1516 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, sym_lst, repl_lst);
1517 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, sym_lst, repl_lst);
1518 numex = re_ex + im_ex * replace_with_symbol(I, sym_lst, repl_lst);
1521 // Denominator is always a real integer (see numeric::denom())
1522 return (new lst(numex, denom()))->setflag(status_flags::dynallocated);
1526 /** Fraction cancellation.
1527 * @param n numerator
1528 * @param d denominator
1529 * @return cancelled fraction {n, d} as a list */
1530 static ex frac_cancel(const ex &n, const ex &d)
1534 numeric pre_factor = _num1();
1536 //clog << "frac_cancel num = " << num << ", den = " << den << endl;
1538 // Handle special cases where numerator or denominator is 0
1540 return (new lst(_ex0(), _ex1()))->setflag(status_flags::dynallocated);
1541 if (den.expand().is_zero())
1542 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
1544 // Bring numerator and denominator to Z[X] by multiplying with
1545 // LCM of all coefficients' denominators
1546 numeric num_lcm = lcm_of_coefficients_denominators(num);
1547 numeric den_lcm = lcm_of_coefficients_denominators(den);
1548 num = multiply_lcm(num, num_lcm);
1549 den = multiply_lcm(den, den_lcm);
1550 pre_factor = den_lcm / num_lcm;
1552 // Cancel GCD from numerator and denominator
1554 if (gcd(num, den, &cnum, &cden, false) != _ex1()) {
1559 // Make denominator unit normal (i.e. coefficient of first symbol
1560 // as defined by get_first_symbol() is made positive)
1562 if (get_first_symbol(den, x)) {
1563 GINAC_ASSERT(is_ex_exactly_of_type(den.unit(*x),numeric));
1564 if (ex_to_numeric(den.unit(*x)).is_negative()) {
1570 // Return result as list
1571 //clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << endl;
1572 return (new lst(num * pre_factor.numer(), den * pre_factor.denom()))->setflag(status_flags::dynallocated);
1576 /** Implementation of ex::normal() for a sum. It expands terms and performs
1577 * fractional addition.
1578 * @see ex::normal */
1579 ex add::normal(lst &sym_lst, lst &repl_lst, int level) const
1581 // Normalize and expand children, chop into summands
1583 o.reserve(seq.size()+1);
1584 epvector::const_iterator it = seq.begin(), itend = seq.end();
1585 while (it != itend) {
1587 // Normalize and expand child
1588 ex n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1).expand();
1590 // If numerator is a sum, chop into summands
1591 if (is_ex_exactly_of_type(n.op(0), add)) {
1592 epvector::const_iterator bit = ex_to_add(n.op(0)).seq.begin(), bitend = ex_to_add(n.op(0)).seq.end();
1593 while (bit != bitend) {
1594 o.push_back((new lst(recombine_pair_to_ex(*bit), n.op(1)))->setflag(status_flags::dynallocated));
1598 // The overall_coeff is already normalized (== rational), we just
1599 // split it into numerator and denominator
1600 GINAC_ASSERT(ex_to_numeric(ex_to_add(n.op(0)).overall_coeff).is_rational());
1601 numeric overall = ex_to_numeric(ex_to_add(n.op(0)).overall_coeff);
1602 o.push_back((new lst(overall.numer(), overall.denom() * n.op(1)))->setflag(status_flags::dynallocated));
1607 o.push_back(overall_coeff.bp->normal(sym_lst, repl_lst, level-1));
1609 // o is now a vector of {numerator, denominator} lists
1611 // Determine common denominator
1613 exvector::const_iterator ait = o.begin(), aitend = o.end();
1614 //clog << "add::normal uses the following summands:\n";
1615 while (ait != aitend) {
1616 //clog << " num = " << ait->op(0) << ", den = " << ait->op(1) << endl;
1617 den = lcm(ait->op(1), den, false);
1620 //clog << " common denominator = " << den << endl;
1623 if (den.is_equal(_ex1())) {
1625 // Common denominator is 1, simply add all numerators
1627 for (ait=o.begin(); ait!=aitend; ait++) {
1628 num_seq.push_back(ait->op(0));
1630 return (new lst((new add(num_seq))->setflag(status_flags::dynallocated), den))->setflag(status_flags::dynallocated);
1634 // Perform fractional addition
1636 for (ait=o.begin(); ait!=aitend; ait++) {
1638 if (!divide(den, ait->op(1), q, false)) {
1639 // should not happen
1640 throw(std::runtime_error("invalid expression in add::normal, division failed"));
1642 num_seq.push_back((ait->op(0) * q).expand());
1644 ex num = (new add(num_seq))->setflag(status_flags::dynallocated);
1646 // Cancel common factors from num/den
1647 return frac_cancel(num, den);
1652 /** Implementation of ex::normal() for a product. It cancels common factors
1654 * @see ex::normal() */
1655 ex mul::normal(lst &sym_lst, lst &repl_lst, int level) const
1657 // Normalize children, separate into numerator and denominator
1661 epvector::const_iterator it = seq.begin(), itend = seq.end();
1662 while (it != itend) {
1663 n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1);
1668 n = overall_coeff.bp->normal(sym_lst, repl_lst, level-1);
1672 // Perform fraction cancellation
1673 return frac_cancel(num, den);
1677 /** Implementation of ex::normal() for powers. It normalizes the basis,
1678 * distributes integer exponents to numerator and denominator, and replaces
1679 * non-integer powers by temporary symbols.
1680 * @see ex::normal */
1681 ex power::normal(lst &sym_lst, lst &repl_lst, int level) const
1684 ex n = basis.bp->normal(sym_lst, repl_lst, level-1);
1686 if (exponent.info(info_flags::integer)) {
1688 if (exponent.info(info_flags::positive)) {
1690 // (a/b)^n -> {a^n, b^n}
1691 return (new lst(power(n.op(0), exponent), power(n.op(1), exponent)))->setflag(status_flags::dynallocated);
1693 } else if (exponent.info(info_flags::negative)) {
1695 // (a/b)^-n -> {b^n, a^n}
1696 return (new lst(power(n.op(1), -exponent), power(n.op(0), -exponent)))->setflag(status_flags::dynallocated);
1701 if (exponent.info(info_flags::positive)) {
1703 // (a/b)^x -> {sym((a/b)^x), 1}
1704 return (new lst(replace_with_symbol(power(n.op(0) / n.op(1), exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1706 } else if (exponent.info(info_flags::negative)) {
1708 if (n.op(1).is_equal(_ex1())) {
1710 // a^-x -> {1, sym(a^x)}
1711 return (new lst(_ex1(), replace_with_symbol(power(n.op(0), -exponent), sym_lst, repl_lst)))->setflag(status_flags::dynallocated);
1715 // (a/b)^-x -> {sym((b/a)^x), 1}
1716 return (new lst(replace_with_symbol(power(n.op(1) / n.op(0), -exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1719 } else { // exponent not numeric
1721 // (a/b)^x -> {sym((a/b)^x, 1}
1722 return (new lst(replace_with_symbol(power(n.op(0) / n.op(1), exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1728 /** Implementation of ex::normal() for pseries. It normalizes each coefficient and
1729 * replaces the series by a temporary symbol.
1730 * @see ex::normal */
1731 ex pseries::normal(lst &sym_lst, lst &repl_lst, int level) const
1734 new_seq.reserve(seq.size());
1736 epvector::const_iterator it = seq.begin(), itend = seq.end();
1737 while (it != itend) {
1738 new_seq.push_back(expair(it->rest.normal(), it->coeff));
1741 ex n = pseries(relational(var,point), new_seq);
1742 return (new lst(replace_with_symbol(n, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1746 /** Normalization of rational functions.
1747 * This function converts an expression to its normal form
1748 * "numerator/denominator", where numerator and denominator are (relatively
1749 * prime) polynomials. Any subexpressions which are not rational functions
1750 * (like non-rational numbers, non-integer powers or functions like Sin(),
1751 * Cos() etc.) are replaced by temporary symbols which are re-substituted by
1752 * the (normalized) subexpressions before normal() returns (this way, any
1753 * expression can be treated as a rational function). normal() is applied
1754 * recursively to arguments of functions etc.
1756 * @param level maximum depth of recursion
1757 * @return normalized expression */
1758 ex ex::normal(int level) const
1760 lst sym_lst, repl_lst;
1762 ex e = bp->normal(sym_lst, repl_lst, level);
1763 GINAC_ASSERT(is_ex_of_type(e, lst));
1765 // Re-insert replaced symbols
1766 if (sym_lst.nops() > 0)
1767 e = e.subs(sym_lst, repl_lst);
1769 // Convert {numerator, denominator} form back to fraction
1770 return e.op(0) / e.op(1);
1773 /** Numerator of an expression. If the expression is not of the normal form
1774 * "numerator/denominator", it is first converted to this form and then the
1775 * numerator is returned.
1778 * @return numerator */
1779 ex ex::numer(void) const
1781 lst sym_lst, repl_lst;
1783 ex e = bp->normal(sym_lst, repl_lst, 0);
1784 GINAC_ASSERT(is_ex_of_type(e, lst));
1786 // Re-insert replaced symbols
1787 if (sym_lst.nops() > 0)
1788 return e.op(0).subs(sym_lst, repl_lst);
1793 /** Denominator of an expression. If the expression is not of the normal form
1794 * "numerator/denominator", it is first converted to this form and then the
1795 * denominator is returned.
1798 * @return denominator */
1799 ex ex::denom(void) const
1801 lst sym_lst, repl_lst;
1803 ex e = bp->normal(sym_lst, repl_lst, 0);
1804 GINAC_ASSERT(is_ex_of_type(e, lst));
1806 // Re-insert replaced symbols
1807 if (sym_lst.nops() > 0)
1808 return e.op(1).subs(sym_lst, repl_lst);
1813 #ifndef NO_NAMESPACE_GINAC
1814 } // namespace GiNaC
1815 #endif // ndef NO_NAMESPACE_GINAC