]> www.ginac.de Git - ginac.git/blob - ginac/normal.cpp
8a9bc0f45c71e955b9f7ab60636df87e1884ad92
[ginac.git] / ginac / normal.cpp
1 /** @file normal.cpp
2  *
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.
7  */
8
9 /*
10  *  GiNaC Copyright (C) 1999-2000 Johannes Gutenberg University Mainz, Germany
11  *
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.
16  *
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.
21  *
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
25  */
26
27 #include <stdexcept>
28 #include <algorithm>
29 #include <map>
30
31 #include "normal.h"
32 #include "basic.h"
33 #include "ex.h"
34 #include "add.h"
35 #include "constant.h"
36 #include "expairseq.h"
37 #include "fail.h"
38 #include "indexed.h"
39 #include "inifcns.h"
40 #include "lst.h"
41 #include "mul.h"
42 #include "ncmul.h"
43 #include "numeric.h"
44 #include "power.h"
45 #include "relational.h"
46 #include "pseries.h"
47 #include "symbol.h"
48 #include "utils.h"
49
50 #ifndef NO_NAMESPACE_GINAC
51 namespace GiNaC {
52 #endif // ndef NO_NAMESPACE_GINAC
53
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
58
59 // Set this if you want divide_in_z() to use remembering
60 #define USE_REMEMBER 1
61
62
63 /** Return pointer to first symbol found in expression.  Due to GiNaCĀ“s
64  *  internal ordering of terms, it may not be obvious which symbol this
65  *  function returns for a given expression.
66  *
67  *  @param e  expression to search
68  *  @param x  pointer to first symbol found (returned)
69  *  @return "false" if no symbol was found, "true" otherwise */
70
71 static bool get_first_symbol(const ex &e, const symbol *&x)
72 {
73     if (is_ex_exactly_of_type(e, symbol)) {
74         x = static_cast<symbol *>(e.bp);
75         return true;
76     } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
77         for (unsigned i=0; i<e.nops(); i++)
78             if (get_first_symbol(e.op(i), x))
79                 return true;
80     } else if (is_ex_exactly_of_type(e, power)) {
81         if (get_first_symbol(e.op(0), x))
82             return true;
83     }
84     return false;
85 }
86
87
88 /*
89  *  Statistical information about symbols in polynomials
90  */
91
92 /** This structure holds information about the highest and lowest degrees
93  *  in which a symbol appears in two multivariate polynomials "a" and "b".
94  *  A vector of these structures with information about all symbols in
95  *  two polynomials can be created with the function get_symbol_stats().
96  *
97  *  @see get_symbol_stats */
98 struct sym_desc {
99     /** Pointer to symbol */
100     const symbol *sym;
101
102     /** Highest degree of symbol in polynomial "a" */
103     int deg_a;
104
105     /** Highest degree of symbol in polynomial "b" */
106     int deg_b;
107
108     /** Lowest degree of symbol in polynomial "a" */
109     int ldeg_a;
110
111     /** Lowest degree of symbol in polynomial "b" */
112     int ldeg_b;
113
114     /** Minimum of ldeg_a and ldeg_b (Used for sorting) */
115     int min_deg;
116
117     /** Commparison operator for sorting */
118     bool operator<(const sym_desc &x) const {return min_deg < x.min_deg;}
119 };
120
121 // Vector of sym_desc structures
122 typedef vector<sym_desc> sym_desc_vec;
123
124 // Add symbol the sym_desc_vec (used internally by get_symbol_stats())
125 static void add_symbol(const symbol *s, sym_desc_vec &v)
126 {
127     sym_desc_vec::iterator it = v.begin(), itend = v.end();
128     while (it != itend) {
129         if (it->sym->compare(*s) == 0)  // If it's already in there, don't add it a second time
130             return;
131         it++;
132     }
133     sym_desc d;
134     d.sym = s;
135     v.push_back(d);
136 }
137
138 // Collect all symbols of an expression (used internally by get_symbol_stats())
139 static void collect_symbols(const ex &e, sym_desc_vec &v)
140 {
141     if (is_ex_exactly_of_type(e, symbol)) {
142         add_symbol(static_cast<symbol *>(e.bp), v);
143     } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
144         for (unsigned i=0; i<e.nops(); i++)
145             collect_symbols(e.op(i), v);
146     } else if (is_ex_exactly_of_type(e, power)) {
147         collect_symbols(e.op(0), v);
148     }
149 }
150
151 /** Collect statistical information about symbols in polynomials.
152  *  This function fills in a vector of "sym_desc" structs which contain
153  *  information about the highest and lowest degrees of all symbols that
154  *  appear in two polynomials. The vector is then sorted by minimum
155  *  degree (lowest to highest). The information gathered by this
156  *  function is used by the GCD routines to identify trivial factors
157  *  and to determine which variable to choose as the main variable
158  *  for GCD computation.
159  *
160  *  @param a  first multivariate polynomial
161  *  @param b  second multivariate polynomial
162  *  @param v  vector of sym_desc structs (filled in) */
163
164 static void get_symbol_stats(const ex &a, const ex &b, sym_desc_vec &v)
165 {
166     collect_symbols(a.eval(), v);   // eval() to expand assigned symbols
167     collect_symbols(b.eval(), v);
168     sym_desc_vec::iterator it = v.begin(), itend = v.end();
169     while (it != itend) {
170         int deg_a = a.degree(*(it->sym));
171         int deg_b = b.degree(*(it->sym));
172         it->deg_a = deg_a;
173         it->deg_b = deg_b;
174         it->min_deg = min(deg_a, deg_b);
175         it->ldeg_a = a.ldegree(*(it->sym));
176         it->ldeg_b = b.ldegree(*(it->sym));
177         it++;
178     }
179     sort(v.begin(), v.end());
180 }
181
182
183 /*
184  *  Computation of LCM of denominators of coefficients of a polynomial
185  */
186
187 // Compute LCM of denominators of coefficients by going through the
188 // expression recursively (used internally by lcm_of_coefficients_denominators())
189 static numeric lcmcoeff(const ex &e, const numeric &l)
190 {
191     if (e.info(info_flags::rational))
192         return lcm(ex_to_numeric(e).denom(), l);
193     else if (is_ex_exactly_of_type(e, add)) {
194         numeric c = _num1();
195         for (unsigned i=0; i<e.nops(); i++)
196             c = lcmcoeff(e.op(i), c);
197         return lcm(c, l);
198     } else if (is_ex_exactly_of_type(e, mul)) {
199         numeric c = _num1();
200         for (unsigned i=0; i<e.nops(); i++)
201             c *= lcmcoeff(e.op(i), _num1());
202         return lcm(c, l);
203     } else if (is_ex_exactly_of_type(e, power))
204         return pow(lcmcoeff(e.op(0), l), ex_to_numeric(e.op(1)));
205     return l;
206 }
207
208 /** Compute LCM of denominators of coefficients of a polynomial.
209  *  Given a polynomial with rational coefficients, this function computes
210  *  the LCM of the denominators of all coefficients. This can be used
211  *  to bring a polynomial from Q[X] to Z[X].
212  *
213  *  @param e  multivariate polynomial (need not be expanded)
214  *  @return LCM of denominators of coefficients */
215
216 static numeric lcm_of_coefficients_denominators(const ex &e)
217 {
218     return lcmcoeff(e, _num1());
219 }
220
221 /** Bring polynomial from Q[X] to Z[X] by multiplying in the previously
222  *  determined LCM of the coefficient's denominators.
223  *
224  *  @param e  multivariate polynomial (need not be expanded)
225  *  @param lcm  LCM to multiply in */
226
227 static ex multiply_lcm(const ex &e, const ex &lcm)
228 {
229         if (is_ex_exactly_of_type(e, mul)) {
230                 ex c = _ex1();
231                 for (unsigned i=0; i<e.nops(); i++)
232                         c *= multiply_lcm(e.op(i), lcmcoeff(e.op(i), _num1()));
233                 return c;
234         } else if (is_ex_exactly_of_type(e, add)) {
235                 ex c = _ex0();
236                 for (unsigned i=0; i<e.nops(); i++)
237                         c += multiply_lcm(e.op(i), lcm);
238                 return c;
239         } else if (is_ex_exactly_of_type(e, power)) {
240                 return pow(multiply_lcm(e.op(0), pow(lcm, 1/e.op(1))), e.op(1));
241         } else
242                 return e * lcm;
243 }
244
245
246 /** Compute the integer content (= GCD of all numeric coefficients) of an
247  *  expanded polynomial.
248  *
249  *  @param e  expanded polynomial
250  *  @return integer content */
251
252 numeric ex::integer_content(void) const
253 {
254     GINAC_ASSERT(bp!=0);
255     return bp->integer_content();
256 }
257
258 numeric basic::integer_content(void) const
259 {
260     return _num1();
261 }
262
263 numeric numeric::integer_content(void) const
264 {
265     return abs(*this);
266 }
267
268 numeric add::integer_content(void) const
269 {
270     epvector::const_iterator it = seq.begin();
271     epvector::const_iterator itend = seq.end();
272     numeric c = _num0();
273     while (it != itend) {
274         GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
275         GINAC_ASSERT(is_ex_exactly_of_type(it->coeff,numeric));
276         c = gcd(ex_to_numeric(it->coeff), c);
277         it++;
278     }
279     GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
280     c = gcd(ex_to_numeric(overall_coeff),c);
281     return c;
282 }
283
284 numeric mul::integer_content(void) const
285 {
286 #ifdef DO_GINAC_ASSERT
287     epvector::const_iterator it = seq.begin();
288     epvector::const_iterator itend = seq.end();
289     while (it != itend) {
290         GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
291         ++it;
292     }
293 #endif // def DO_GINAC_ASSERT
294     GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
295     return abs(ex_to_numeric(overall_coeff));
296 }
297
298
299 /*
300  *  Polynomial quotients and remainders
301  */
302
303 /** Quotient q(x) of polynomials a(x) and b(x) in Q[x].
304  *  It satisfies a(x)=b(x)*q(x)+r(x).
305  *
306  *  @param a  first polynomial in x (dividend)
307  *  @param b  second polynomial in x (divisor)
308  *  @param x  a and b are polynomials in x
309  *  @param check_args  check whether a and b are polynomials with rational
310  *         coefficients (defaults to "true")
311  *  @return quotient of a and b in Q[x] */
312
313 ex quo(const ex &a, const ex &b, const symbol &x, bool check_args)
314 {
315     if (b.is_zero())
316         throw(std::overflow_error("quo: division by zero"));
317     if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
318         return a / b;
319 #if FAST_COMPARE
320     if (a.is_equal(b))
321         return _ex1();
322 #endif
323     if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
324         throw(std::invalid_argument("quo: arguments must be polynomials over the rationals"));
325
326     // Polynomial long division
327     ex q = _ex0();
328     ex r = a.expand();
329     if (r.is_zero())
330         return r;
331     int bdeg = b.degree(x);
332     int rdeg = r.degree(x);
333     ex blcoeff = b.expand().coeff(x, bdeg);
334     bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
335     while (rdeg >= bdeg) {
336         ex term, rcoeff = r.coeff(x, rdeg);
337         if (blcoeff_is_numeric)
338             term = rcoeff / blcoeff;
339         else {
340             if (!divide(rcoeff, blcoeff, term, false))
341                 return *new ex(fail());
342         }
343         term *= power(x, rdeg - bdeg);
344         q += term;
345         r -= (term * b).expand();
346         if (r.is_zero())
347             break;
348         rdeg = r.degree(x);
349     }
350     return q;
351 }
352
353
354 /** Remainder r(x) of polynomials a(x) and b(x) in Q[x].
355  *  It satisfies a(x)=b(x)*q(x)+r(x).
356  *
357  *  @param a  first polynomial in x (dividend)
358  *  @param b  second polynomial in x (divisor)
359  *  @param x  a and b are polynomials in x
360  *  @param check_args  check whether a and b are polynomials with rational
361  *         coefficients (defaults to "true")
362  *  @return remainder of a(x) and b(x) in Q[x] */
363
364 ex rem(const ex &a, const ex &b, const symbol &x, bool check_args)
365 {
366     if (b.is_zero())
367         throw(std::overflow_error("rem: division by zero"));
368     if (is_ex_exactly_of_type(a, numeric)) {
369         if  (is_ex_exactly_of_type(b, numeric))
370             return _ex0();
371         else
372             return b;
373     }
374 #if FAST_COMPARE
375     if (a.is_equal(b))
376         return _ex0();
377 #endif
378     if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
379         throw(std::invalid_argument("rem: arguments must be polynomials over the rationals"));
380
381     // Polynomial long division
382     ex r = a.expand();
383     if (r.is_zero())
384         return r;
385     int bdeg = b.degree(x);
386     int rdeg = r.degree(x);
387     ex blcoeff = b.expand().coeff(x, bdeg);
388     bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
389     while (rdeg >= bdeg) {
390         ex term, rcoeff = r.coeff(x, rdeg);
391         if (blcoeff_is_numeric)
392             term = rcoeff / blcoeff;
393         else {
394             if (!divide(rcoeff, blcoeff, term, false))
395                 return *new ex(fail());
396         }
397         term *= power(x, rdeg - bdeg);
398         r -= (term * b).expand();
399         if (r.is_zero())
400             break;
401         rdeg = r.degree(x);
402     }
403     return r;
404 }
405
406
407 /** Pseudo-remainder of polynomials a(x) and b(x) in Z[x].
408  *
409  *  @param a  first polynomial in x (dividend)
410  *  @param b  second polynomial in x (divisor)
411  *  @param x  a and b are polynomials in x
412  *  @param check_args  check whether a and b are polynomials with rational
413  *         coefficients (defaults to "true")
414  *  @return pseudo-remainder of a(x) and b(x) in Z[x] */
415
416 ex prem(const ex &a, const ex &b, const symbol &x, bool check_args)
417 {
418     if (b.is_zero())
419         throw(std::overflow_error("prem: division by zero"));
420     if (is_ex_exactly_of_type(a, numeric)) {
421         if (is_ex_exactly_of_type(b, numeric))
422             return _ex0();
423         else
424             return b;
425     }
426     if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
427         throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
428
429     // Polynomial long division
430     ex r = a.expand();
431     ex eb = b.expand();
432     int rdeg = r.degree(x);
433     int bdeg = eb.degree(x);
434     ex blcoeff;
435     if (bdeg <= rdeg) {
436         blcoeff = eb.coeff(x, bdeg);
437         if (bdeg == 0)
438             eb = _ex0();
439         else
440             eb -= blcoeff * power(x, bdeg);
441     } else
442         blcoeff = _ex1();
443
444     int delta = rdeg - bdeg + 1, i = 0;
445     while (rdeg >= bdeg && !r.is_zero()) {
446         ex rlcoeff = r.coeff(x, rdeg);
447         ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
448         if (rdeg == 0)
449             r = _ex0();
450         else
451             r -= rlcoeff * power(x, rdeg);
452         r = (blcoeff * r).expand() - term;
453         rdeg = r.degree(x);
454         i++;
455     }
456     return power(blcoeff, delta - i) * r;
457 }
458
459
460 /** Exact polynomial division of a(X) by b(X) in Q[X].
461  *  
462  *  @param a  first multivariate polynomial (dividend)
463  *  @param b  second multivariate polynomial (divisor)
464  *  @param q  quotient (returned)
465  *  @param check_args  check whether a and b are polynomials with rational
466  *         coefficients (defaults to "true")
467  *  @return "true" when exact division succeeds (quotient returned in q),
468  *          "false" otherwise */
469
470 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
471 {
472     q = _ex0();
473     if (b.is_zero())
474         throw(std::overflow_error("divide: division by zero"));
475     if (is_ex_exactly_of_type(b, numeric)) {
476         q = a / b;
477         return true;
478     } else if (is_ex_exactly_of_type(a, numeric))
479         return false;
480 #if FAST_COMPARE
481     if (a.is_equal(b)) {
482         q = _ex1();
483         return true;
484     }
485 #endif
486     if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
487         throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
488
489     // Find first symbol
490     const symbol *x;
491     if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
492         throw(std::invalid_argument("invalid expression in divide()"));
493
494     // Polynomial long division (recursive)
495     ex r = a.expand();
496     if (r.is_zero())
497         return true;
498     int bdeg = b.degree(*x);
499     int rdeg = r.degree(*x);
500     ex blcoeff = b.expand().coeff(*x, bdeg);
501     bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
502     while (rdeg >= bdeg) {
503         ex term, rcoeff = r.coeff(*x, rdeg);
504         if (blcoeff_is_numeric)
505             term = rcoeff / blcoeff;
506         else
507             if (!divide(rcoeff, blcoeff, term, false))
508                 return false;
509         term *= power(*x, rdeg - bdeg);
510         q += term;
511         r -= (term * b).expand();
512         if (r.is_zero())
513             return true;
514         rdeg = r.degree(*x);
515     }
516     return false;
517 }
518
519
520 #if USE_REMEMBER
521 /*
522  *  Remembering
523  */
524
525 typedef pair<ex, ex> ex2;
526 typedef pair<ex, bool> exbool;
527
528 struct ex2_less {
529     bool operator() (const ex2 p, const ex2 q) const 
530     {
531         return p.first.compare(q.first) < 0 || (!(q.first.compare(p.first) < 0) && p.second.compare(q.second) < 0);        
532     }
533 };
534
535 typedef map<ex2, exbool, ex2_less> ex2_exbool_remember;
536 #endif
537
538
539 /** Exact polynomial division of a(X) by b(X) in Z[X].
540  *  This functions works like divide() but the input and output polynomials are
541  *  in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
542  *  divide(), it doesnĀ“t check whether the input polynomials really are integer
543  *  polynomials, so be careful of what you pass in. Also, you have to run
544  *  get_symbol_stats() over the input polynomials before calling this function
545  *  and pass an iterator to the first element of the sym_desc vector. This
546  *  function is used internally by the heur_gcd().
547  *  
548  *  @param a  first multivariate polynomial (dividend)
549  *  @param b  second multivariate polynomial (divisor)
550  *  @param q  quotient (returned)
551  *  @param var  iterator to first element of vector of sym_desc structs
552  *  @return "true" when exact division succeeds (the quotient is returned in
553  *          q), "false" otherwise.
554  *  @see get_symbol_stats, heur_gcd */
555 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
556 {
557     q = _ex0();
558     if (b.is_zero())
559         throw(std::overflow_error("divide_in_z: division by zero"));
560     if (b.is_equal(_ex1())) {
561         q = a;
562         return true;
563     }
564     if (is_ex_exactly_of_type(a, numeric)) {
565         if (is_ex_exactly_of_type(b, numeric)) {
566             q = a / b;
567             return q.info(info_flags::integer);
568         } else
569             return false;
570     }
571 #if FAST_COMPARE
572     if (a.is_equal(b)) {
573         q = _ex1();
574         return true;
575     }
576 #endif
577
578 #if USE_REMEMBER
579     // Remembering
580     static ex2_exbool_remember dr_remember;
581     ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
582     if (remembered != dr_remember.end()) {
583         q = remembered->second.first;
584         return remembered->second.second;
585     }
586 #endif
587
588     // Main symbol
589     const symbol *x = var->sym;
590
591     // Compare degrees
592     int adeg = a.degree(*x), bdeg = b.degree(*x);
593     if (bdeg > adeg)
594         return false;
595
596 #if 1
597
598     // Polynomial long division (recursive)
599     ex r = a.expand();
600     if (r.is_zero())
601         return true;
602     int rdeg = adeg;
603     ex eb = b.expand();
604     ex blcoeff = eb.coeff(*x, bdeg);
605     while (rdeg >= bdeg) {
606         ex term, rcoeff = r.coeff(*x, rdeg);
607         if (!divide_in_z(rcoeff, blcoeff, term, var+1))
608             break;
609         term = (term * power(*x, rdeg - bdeg)).expand();
610         q += term;
611         r -= (term * eb).expand();
612         if (r.is_zero()) {
613 #if USE_REMEMBER
614             dr_remember[ex2(a, b)] = exbool(q, true);
615 #endif
616             return true;
617         }
618         rdeg = r.degree(*x);
619     }
620 #if USE_REMEMBER
621     dr_remember[ex2(a, b)] = exbool(q, false);
622 #endif
623     return false;
624
625 #else
626
627     // Trial division using polynomial interpolation
628     int i, k;
629
630     // Compute values at evaluation points 0..adeg
631     vector<numeric> alpha; alpha.reserve(adeg + 1);
632     exvector u; u.reserve(adeg + 1);
633     numeric point = _num0();
634     ex c;
635     for (i=0; i<=adeg; i++) {
636         ex bs = b.subs(*x == point);
637         while (bs.is_zero()) {
638             point += _num1();
639             bs = b.subs(*x == point);
640         }
641         if (!divide_in_z(a.subs(*x == point), bs, c, var+1))
642             return false;
643         alpha.push_back(point);
644         u.push_back(c);
645         point += _num1();
646     }
647
648     // Compute inverses
649     vector<numeric> rcp; rcp.reserve(adeg + 1);
650     rcp.push_back(0);
651     for (k=1; k<=adeg; k++) {
652         numeric product = alpha[k] - alpha[0];
653         for (i=1; i<k; i++)
654             product *= alpha[k] - alpha[i];
655         rcp.push_back(product.inverse());
656     }
657
658     // Compute Newton coefficients
659     exvector v; v.reserve(adeg + 1);
660     v.push_back(u[0]);
661     for (k=1; k<=adeg; k++) {
662         ex temp = v[k - 1];
663         for (i=k-2; i>=0; i--)
664             temp = temp * (alpha[k] - alpha[i]) + v[i];
665         v.push_back((u[k] - temp) * rcp[k]);
666     }
667
668     // Convert from Newton form to standard form
669     c = v[adeg];
670     for (k=adeg-1; k>=0; k--)
671         c = c * (*x - alpha[k]) + v[k];
672
673     if (c.degree(*x) == (adeg - bdeg)) {
674         q = c.expand();
675         return true;
676     } else
677         return false;
678 #endif
679 }
680
681
682 /*
683  *  Separation of unit part, content part and primitive part of polynomials
684  */
685
686 /** Compute unit part (= sign of leading coefficient) of a multivariate
687  *  polynomial in Z[x]. The product of unit part, content part, and primitive
688  *  part is the polynomial itself.
689  *
690  *  @param x  variable in which to compute the unit part
691  *  @return unit part
692  *  @see ex::content, ex::primpart */
693 ex ex::unit(const symbol &x) const
694 {
695     ex c = expand().lcoeff(x);
696     if (is_ex_exactly_of_type(c, numeric))
697         return c < _ex0() ? _ex_1() : _ex1();
698     else {
699         const symbol *y;
700         if (get_first_symbol(c, y))
701             return c.unit(*y);
702         else
703             throw(std::invalid_argument("invalid expression in unit()"));
704     }
705 }
706
707
708 /** Compute content part (= unit normal GCD of all coefficients) of a
709  *  multivariate polynomial in Z[x].  The product of unit part, content part,
710  *  and primitive part is the polynomial itself.
711  *
712  *  @param x  variable in which to compute the content part
713  *  @return content part
714  *  @see ex::unit, ex::primpart */
715 ex ex::content(const symbol &x) const
716 {
717     if (is_zero())
718         return _ex0();
719     if (is_ex_exactly_of_type(*this, numeric))
720         return info(info_flags::negative) ? -*this : *this;
721     ex e = expand();
722     if (e.is_zero())
723         return _ex0();
724
725     // First, try the integer content
726     ex c = e.integer_content();
727     ex r = e / c;
728     ex lcoeff = r.lcoeff(x);
729     if (lcoeff.info(info_flags::integer))
730         return c;
731
732     // GCD of all coefficients
733     int deg = e.degree(x);
734     int ldeg = e.ldegree(x);
735     if (deg == ldeg)
736         return e.lcoeff(x) / e.unit(x);
737     c = _ex0();
738     for (int i=ldeg; i<=deg; i++)
739         c = gcd(e.coeff(x, i), c, NULL, NULL, false);
740     return c;
741 }
742
743
744 /** Compute primitive part of a multivariate polynomial in Z[x].
745  *  The product of unit part, content part, and primitive part is the
746  *  polynomial itself.
747  *
748  *  @param x  variable in which to compute the primitive part
749  *  @return primitive part
750  *  @see ex::unit, ex::content */
751 ex ex::primpart(const symbol &x) const
752 {
753     if (is_zero())
754         return _ex0();
755     if (is_ex_exactly_of_type(*this, numeric))
756         return _ex1();
757
758     ex c = content(x);
759     if (c.is_zero())
760         return _ex0();
761     ex u = unit(x);
762     if (is_ex_exactly_of_type(c, numeric))
763         return *this / (c * u);
764     else
765         return quo(*this, c * u, x, false);
766 }
767
768
769 /** Compute primitive part of a multivariate polynomial in Z[x] when the
770  *  content part is already known. This function is faster in computing the
771  *  primitive part than the previous function.
772  *
773  *  @param x  variable in which to compute the primitive part
774  *  @param c  previously computed content part
775  *  @return primitive part */
776
777 ex ex::primpart(const symbol &x, const ex &c) const
778 {
779     if (is_zero())
780         return _ex0();
781     if (c.is_zero())
782         return _ex0();
783     if (is_ex_exactly_of_type(*this, numeric))
784         return _ex1();
785
786     ex u = unit(x);
787     if (is_ex_exactly_of_type(c, numeric))
788         return *this / (c * u);
789     else
790         return quo(*this, c * u, x, false);
791 }
792
793
794 /*
795  *  GCD of multivariate polynomials
796  */
797
798 /** Compute GCD of multivariate polynomials using the subresultant PRS
799  *  algorithm. This function is used internally gy gcd().
800  *
801  *  @param a  first multivariate polynomial
802  *  @param b  second multivariate polynomial
803  *  @param x  pointer to symbol (main variable) in which to compute the GCD in
804  *  @return the GCD as a new expression
805  *  @see gcd */
806
807 static ex sr_gcd(const ex &a, const ex &b, const symbol *x)
808 {
809     // Sort c and d so that c has higher degree
810     ex c, d;
811     int adeg = a.degree(*x), bdeg = b.degree(*x);
812     int cdeg, ddeg;
813     if (adeg >= bdeg) {
814         c = a;
815         d = b;
816         cdeg = adeg;
817         ddeg = bdeg;
818     } else {
819         c = b;
820         d = a;
821         cdeg = bdeg;
822         ddeg = adeg;
823     }
824
825     // Remove content from c and d, to be attached to GCD later
826     ex cont_c = c.content(*x);
827     ex cont_d = d.content(*x);
828     ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
829     if (ddeg == 0)
830         return gamma;
831     c = c.primpart(*x, cont_c);
832     d = d.primpart(*x, cont_d);
833
834     // First element of subresultant sequence
835     ex r = _ex0(), ri = _ex1(), psi = _ex1();
836     int delta = cdeg - ddeg;
837
838     for (;;) {
839         // Calculate polynomial pseudo-remainder
840         r = prem(c, d, *x, false);
841         if (r.is_zero())
842             return gamma * d.primpart(*x);
843         c = d;
844         cdeg = ddeg;
845         if (!divide(r, ri * power(psi, delta), d, false))
846             throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
847         ddeg = d.degree(*x);
848         if (ddeg == 0) {
849             if (is_ex_exactly_of_type(r, numeric))
850                 return gamma;
851             else
852                 return gamma * r.primpart(*x);
853         }
854
855         // Next element of subresultant sequence
856         ri = c.expand().lcoeff(*x);
857         if (delta == 1)
858             psi = ri;
859         else if (delta)
860             divide(power(ri, delta), power(psi, delta-1), psi, false);
861         delta = cdeg - ddeg;
862     }
863 }
864
865
866 /** Return maximum (absolute value) coefficient of a polynomial.
867  *  This function is used internally by heur_gcd().
868  *
869  *  @param e  expanded multivariate polynomial
870  *  @return maximum coefficient
871  *  @see heur_gcd */
872
873 numeric ex::max_coefficient(void) const
874 {
875     GINAC_ASSERT(bp!=0);
876     return bp->max_coefficient();
877 }
878
879 numeric basic::max_coefficient(void) const
880 {
881     return _num1();
882 }
883
884 numeric numeric::max_coefficient(void) const
885 {
886     return abs(*this);
887 }
888
889 numeric add::max_coefficient(void) const
890 {
891     epvector::const_iterator it = seq.begin();
892     epvector::const_iterator itend = seq.end();
893     GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
894     numeric cur_max = abs(ex_to_numeric(overall_coeff));
895     while (it != itend) {
896         numeric a;
897         GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
898         a = abs(ex_to_numeric(it->coeff));
899         if (a > cur_max)
900             cur_max = a;
901         it++;
902     }
903     return cur_max;
904 }
905
906 numeric mul::max_coefficient(void) const
907 {
908 #ifdef DO_GINAC_ASSERT
909     epvector::const_iterator it = seq.begin();
910     epvector::const_iterator itend = seq.end();
911     while (it != itend) {
912         GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
913         it++;
914     }
915 #endif // def DO_GINAC_ASSERT
916     GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
917     return abs(ex_to_numeric(overall_coeff));
918 }
919
920
921 /** Apply symmetric modular homomorphism to a multivariate polynomial.
922  *  This function is used internally by heur_gcd().
923  *
924  *  @param e  expanded multivariate polynomial
925  *  @param xi  modulus
926  *  @return mapped polynomial
927  *  @see heur_gcd */
928
929 ex ex::smod(const numeric &xi) const
930 {
931     GINAC_ASSERT(bp!=0);
932     return bp->smod(xi);
933 }
934
935 ex basic::smod(const numeric &xi) const
936 {
937     return *this;
938 }
939
940 ex numeric::smod(const numeric &xi) const
941 {
942 #ifndef NO_NAMESPACE_GINAC
943     return GiNaC::smod(*this, xi);
944 #else // ndef NO_NAMESPACE_GINAC
945     return ::smod(*this, xi);
946 #endif // ndef NO_NAMESPACE_GINAC
947 }
948
949 ex add::smod(const numeric &xi) const
950 {
951     epvector newseq;
952     newseq.reserve(seq.size()+1);
953     epvector::const_iterator it = seq.begin();
954     epvector::const_iterator itend = seq.end();
955     while (it != itend) {
956         GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
957 #ifndef NO_NAMESPACE_GINAC
958         numeric coeff = GiNaC::smod(ex_to_numeric(it->coeff), xi);
959 #else // ndef NO_NAMESPACE_GINAC
960         numeric coeff = ::smod(ex_to_numeric(it->coeff), xi);
961 #endif // ndef NO_NAMESPACE_GINAC
962         if (!coeff.is_zero())
963             newseq.push_back(expair(it->rest, coeff));
964         it++;
965     }
966     GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
967 #ifndef NO_NAMESPACE_GINAC
968     numeric coeff = GiNaC::smod(ex_to_numeric(overall_coeff), xi);
969 #else // ndef NO_NAMESPACE_GINAC
970     numeric coeff = ::smod(ex_to_numeric(overall_coeff), xi);
971 #endif // ndef NO_NAMESPACE_GINAC
972     return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
973 }
974
975 ex mul::smod(const numeric &xi) const
976 {
977 #ifdef DO_GINAC_ASSERT
978     epvector::const_iterator it = seq.begin();
979     epvector::const_iterator itend = seq.end();
980     while (it != itend) {
981         GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
982         it++;
983     }
984 #endif // def DO_GINAC_ASSERT
985     mul * mulcopyp=new mul(*this);
986     GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
987 #ifndef NO_NAMESPACE_GINAC
988     mulcopyp->overall_coeff = GiNaC::smod(ex_to_numeric(overall_coeff),xi);
989 #else // ndef NO_NAMESPACE_GINAC
990     mulcopyp->overall_coeff = ::smod(ex_to_numeric(overall_coeff),xi);
991 #endif // ndef NO_NAMESPACE_GINAC
992     mulcopyp->clearflag(status_flags::evaluated);
993     mulcopyp->clearflag(status_flags::hash_calculated);
994     return mulcopyp->setflag(status_flags::dynallocated);
995 }
996
997
998 /** Exception thrown by heur_gcd() to signal failure. */
999 class gcdheu_failed {};
1000
1001 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1002  *  get_symbol_stats() must have been called previously with the input
1003  *  polynomials and an iterator to the first element of the sym_desc vector
1004  *  passed in. This function is used internally by gcd().
1005  *
1006  *  @param a  first multivariate polynomial (expanded)
1007  *  @param b  second multivariate polynomial (expanded)
1008  *  @param ca  cofactor of polynomial a (returned), NULL to suppress
1009  *             calculation of cofactor
1010  *  @param cb  cofactor of polynomial b (returned), NULL to suppress
1011  *             calculation of cofactor
1012  *  @param var iterator to first element of vector of sym_desc structs
1013  *  @return the GCD as a new expression
1014  *  @see gcd
1015  *  @exception gcdheu_failed() */
1016
1017 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
1018 {
1019     if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1020         numeric g = gcd(ex_to_numeric(a), ex_to_numeric(b));
1021         numeric rg;
1022         if (ca || cb)
1023             rg = g.inverse();
1024         if (ca)
1025             *ca = ex_to_numeric(a).mul(rg);
1026         if (cb)
1027             *cb = ex_to_numeric(b).mul(rg);
1028         return g;
1029     }
1030
1031     // The first symbol is our main variable
1032     const symbol *x = var->sym;
1033
1034     // Remove integer content
1035     numeric gc = gcd(a.integer_content(), b.integer_content());
1036     numeric rgc = gc.inverse();
1037     ex p = a * rgc;
1038     ex q = b * rgc;
1039     int maxdeg = max(p.degree(*x), q.degree(*x));
1040
1041     // Find evaluation point
1042     numeric mp = p.max_coefficient(), mq = q.max_coefficient();
1043     numeric xi;
1044     if (mp > mq)
1045         xi = mq * _num2() + _num2();
1046     else
1047         xi = mp * _num2() + _num2();
1048
1049     // 6 tries maximum
1050     for (int t=0; t<6; t++) {
1051         if (xi.int_length() * maxdeg > 50000)
1052             throw gcdheu_failed();
1053
1054         // Apply evaluation homomorphism and calculate GCD
1055         ex gamma = heur_gcd(p.subs(*x == xi), q.subs(*x == xi), NULL, NULL, var+1).expand();
1056         if (!is_ex_exactly_of_type(gamma, fail)) {
1057
1058             // Reconstruct polynomial from GCD of mapped polynomials
1059             ex g = _ex0();
1060             numeric rxi = xi.inverse();
1061             for (int i=0; !gamma.is_zero(); i++) {
1062                 ex gi = gamma.smod(xi);
1063                 g += gi * power(*x, i);
1064                 gamma = (gamma - gi) * rxi;
1065             }
1066             // Remove integer content
1067             g /= g.integer_content();
1068
1069             // If the calculated polynomial divides both a and b, this is the GCD
1070             ex dummy;
1071             if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1072                 g *= gc;
1073                 ex lc = g.lcoeff(*x);
1074                 if (is_ex_exactly_of_type(lc, numeric) && lc.compare(_ex0()) < 0)
1075                     return -g;
1076                 else
1077                     return g;
1078             }
1079         }
1080
1081         // Next evaluation point
1082         xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1083     }
1084     return *new ex(fail());
1085 }
1086
1087
1088 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1089  *  and b(X) in Z[X].
1090  *
1091  *  @param a  first multivariate polynomial
1092  *  @param b  second multivariate polynomial
1093  *  @param check_args  check whether a and b are polynomials with rational
1094  *         coefficients (defaults to "true")
1095  *  @return the GCD as a new expression */
1096
1097 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1098 {
1099         // Partially factored cases (to avoid expanding large expressions)
1100         if (is_ex_exactly_of_type(a, mul)) {
1101                 if (is_ex_exactly_of_type(b, mul) && b.nops() > a.nops())
1102                         goto factored_b;
1103 factored_a:
1104                 ex g = _ex1();
1105                 ex acc_ca = _ex1();
1106                 ex part_b = b;
1107                 for (unsigned i=0; i<a.nops(); i++) {
1108                         ex part_ca, part_cb;
1109                         g *= gcd(a.op(i), part_b, &part_ca, &part_cb, check_args);
1110                         acc_ca *= part_ca;
1111                         part_b = part_cb;
1112                 }
1113                 if (ca)
1114                         *ca = acc_ca;
1115                 if (cb)
1116                         *cb = part_b;
1117                 return g;
1118         } else if (is_ex_exactly_of_type(b, mul)) {
1119                 if (is_ex_exactly_of_type(a, mul) && a.nops() > b.nops())
1120                         goto factored_a;
1121 factored_b:
1122                 ex g = _ex1();
1123                 ex acc_cb = _ex1();
1124                 ex part_a = a;
1125                 for (unsigned i=0; i<b.nops(); i++) {
1126                         ex part_ca, part_cb;
1127                         g *= gcd(part_a, b.op(i), &part_ca, &part_cb, check_args);
1128                         acc_cb *= part_cb;
1129                         part_a = part_ca;
1130                 }
1131                 if (ca)
1132                         *ca = part_a;
1133                 if (cb)
1134                         *cb = acc_cb;
1135                 return g;
1136         }
1137
1138     // Some trivial cases
1139         ex aex = a.expand(), bex = b.expand();
1140     if (aex.is_zero()) {
1141         if (ca)
1142             *ca = _ex0();
1143         if (cb)
1144             *cb = _ex1();
1145         return b;
1146     }
1147     if (bex.is_zero()) {
1148         if (ca)
1149             *ca = _ex1();
1150         if (cb)
1151             *cb = _ex0();
1152         return a;
1153     }
1154     if (aex.is_equal(_ex1()) || bex.is_equal(_ex1())) {
1155         if (ca)
1156             *ca = a;
1157         if (cb)
1158             *cb = b;
1159         return _ex1();
1160     }
1161 #if FAST_COMPARE
1162     if (a.is_equal(b)) {
1163         if (ca)
1164             *ca = _ex1();
1165         if (cb)
1166             *cb = _ex1();
1167         return a;
1168     }
1169 #endif
1170     if (is_ex_exactly_of_type(aex, numeric) && is_ex_exactly_of_type(bex, numeric)) {
1171         numeric g = gcd(ex_to_numeric(aex), ex_to_numeric(bex));
1172         if (ca)
1173             *ca = ex_to_numeric(aex) / g;
1174         if (cb)
1175             *cb = ex_to_numeric(bex) / g;
1176         return g;
1177     }
1178     if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)) {
1179         throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1180     }
1181
1182     // Gather symbol statistics
1183     sym_desc_vec sym_stats;
1184     get_symbol_stats(a, b, sym_stats);
1185
1186     // The symbol with least degree is our main variable
1187     sym_desc_vec::const_iterator var = sym_stats.begin();
1188     const symbol *x = var->sym;
1189
1190     // Cancel trivial common factor
1191     int ldeg_a = var->ldeg_a;
1192     int ldeg_b = var->ldeg_b;
1193     int min_ldeg = min(ldeg_a, ldeg_b);
1194     if (min_ldeg > 0) {
1195         ex common = power(*x, min_ldeg);
1196 //clog << "trivial common factor " << common << endl;
1197         return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1198     }
1199
1200     // Try to eliminate variables
1201     if (var->deg_a == 0) {
1202 //clog << "eliminating variable " << *x << " from b" << endl;
1203         ex c = bex.content(*x);
1204         ex g = gcd(aex, c, ca, cb, false);
1205         if (cb)
1206             *cb *= bex.unit(*x) * bex.primpart(*x, c);
1207         return g;
1208     } else if (var->deg_b == 0) {
1209 //clog << "eliminating variable " << *x << " from a" << endl;
1210         ex c = aex.content(*x);
1211         ex g = gcd(c, bex, ca, cb, false);
1212         if (ca)
1213             *ca *= aex.unit(*x) * aex.primpart(*x, c);
1214         return g;
1215     }
1216
1217     // Try heuristic algorithm first, fall back to PRS if that failed
1218     ex g;
1219     try {
1220         g = heur_gcd(aex, bex, ca, cb, var);
1221     } catch (gcdheu_failed) {
1222         g = *new ex(fail());
1223     }
1224     if (is_ex_exactly_of_type(g, fail)) {
1225 //clog << "heuristics failed" << endl;
1226         g = sr_gcd(aex, bex, x);
1227         if (ca)
1228             divide(aex, g, *ca, false);
1229         if (cb)
1230             divide(bex, g, *cb, false);
1231     }
1232     return g;
1233 }
1234
1235
1236 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1237  *
1238  *  @param a  first multivariate polynomial
1239  *  @param b  second multivariate polynomial
1240  *  @param check_args  check whether a and b are polynomials with rational
1241  *         coefficients (defaults to "true")
1242  *  @return the LCM as a new expression */
1243 ex lcm(const ex &a, const ex &b, bool check_args)
1244 {
1245     if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
1246         return gcd(ex_to_numeric(a), ex_to_numeric(b));
1247     if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1248         throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1249     
1250     ex ca, cb;
1251     ex g = gcd(a, b, &ca, &cb, false);
1252     return ca * cb * g;
1253 }
1254
1255
1256 /*
1257  *  Square-free factorization
1258  */
1259
1260 // Univariate GCD of polynomials in Q[x] (used internally by sqrfree()).
1261 // a and b can be multivariate polynomials but they are treated as univariate polynomials in x.
1262 static ex univariate_gcd(const ex &a, const ex &b, const symbol &x)
1263 {
1264     if (a.is_zero())
1265         return b;
1266     if (b.is_zero())
1267         return a;
1268     if (a.is_equal(_ex1()) || b.is_equal(_ex1()))
1269         return _ex1();
1270     if (is_ex_of_type(a, numeric) && is_ex_of_type(b, numeric))
1271         return gcd(ex_to_numeric(a), ex_to_numeric(b));
1272     if (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1273         throw(std::invalid_argument("univariate_gcd: arguments must be polynomials over the rationals"));
1274
1275     // Euclidean algorithm
1276     ex c, d, r;
1277     if (a.degree(x) >= b.degree(x)) {
1278         c = a;
1279         d = b;
1280     } else {
1281         c = b;
1282         d = a;
1283     }
1284     for (;;) {
1285         r = rem(c, d, x, false);
1286         if (r.is_zero())
1287             break;
1288         c = d;
1289         d = r;
1290     }
1291     return d / d.lcoeff(x);
1292 }
1293
1294
1295 /** Compute square-free factorization of multivariate polynomial a(x) using
1296  *  YunĀ“s algorithm.
1297  *
1298  * @param a  multivariate polynomial
1299  * @param x  variable to factor in
1300  * @return factored polynomial */
1301 ex sqrfree(const ex &a, const symbol &x)
1302 {
1303     int i = 1;
1304     ex res = _ex1();
1305     ex b = a.diff(x);
1306     ex c = univariate_gcd(a, b, x);
1307     ex w;
1308     if (c.is_equal(_ex1())) {
1309         w = a;
1310     } else {
1311         w = quo(a, c, x);
1312         ex y = quo(b, c, x);
1313         ex z = y - w.diff(x);
1314         while (!z.is_zero()) {
1315             ex g = univariate_gcd(w, z, x);
1316             res *= power(g, i);
1317             w = quo(w, g, x);
1318             y = quo(z, g, x);
1319             z = y - w.diff(x);
1320             i++;
1321         }
1322     }
1323     return res * power(w, i);
1324 }
1325
1326
1327 /*
1328  *  Normal form of rational functions
1329  */
1330
1331 // Create a symbol for replacing the expression "e" (or return a previously
1332 // assigned symbol). The symbol is appended to sym_list and returned, the
1333 // expression is appended to repl_list.
1334 static ex replace_with_symbol(const ex &e, lst &sym_lst, lst &repl_lst)
1335 {
1336     // Expression already in repl_lst? Then return the assigned symbol
1337     for (unsigned i=0; i<repl_lst.nops(); i++)
1338         if (repl_lst.op(i).is_equal(e))
1339             return sym_lst.op(i);
1340
1341     // Otherwise create new symbol and add to list, taking care that the
1342         // replacement expression doesn't contain symbols from the sym_lst
1343         // because subs() is not recursive
1344         symbol s;
1345         ex es(s);
1346         ex e_replaced = e.subs(sym_lst, repl_lst);
1347     sym_lst.append(es);
1348     repl_lst.append(e_replaced);
1349     return es;
1350 }
1351
1352
1353 /** Default implementation of ex::normal(). It replaces the object with a
1354  *  temporary symbol.
1355  *  @see ex::normal */
1356 ex basic::normal(lst &sym_lst, lst &repl_lst, int level) const
1357 {
1358     return replace_with_symbol(*this, sym_lst, repl_lst);
1359 }
1360
1361
1362 /** Implementation of ex::normal() for symbols. This returns the unmodifies symbol.
1363  *  @see ex::normal */
1364 ex symbol::normal(lst &sym_lst, lst &repl_lst, int level) const
1365 {
1366     return *this;
1367 }
1368
1369
1370 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1371  *  into re+I*im and replaces I and non-rational real numbers with a temporary
1372  *  symbol.
1373  *  @see ex::normal */
1374 ex numeric::normal(lst &sym_lst, lst &repl_lst, int level) const
1375 {
1376     if (is_real())
1377         if (is_rational())
1378             return *this;
1379         else
1380             return replace_with_symbol(*this, sym_lst, repl_lst);
1381     else { // complex
1382         numeric re = real(), im = imag();
1383         ex re_ex = re.is_rational() ? re : replace_with_symbol(re, sym_lst, repl_lst);
1384         ex im_ex = im.is_rational() ? im : replace_with_symbol(im, sym_lst, repl_lst);
1385         return re_ex + im_ex * replace_with_symbol(I, sym_lst, repl_lst);
1386     }
1387 }
1388
1389
1390 /** Fraction cancellation.
1391  *  @param n  numerator
1392  *  @param d  denominator
1393  *  @return cancelled fraction n/d */
1394 static ex frac_cancel(const ex &n, const ex &d)
1395 {
1396     ex num = n;
1397     ex den = d;
1398     ex pre_factor = _ex1();
1399
1400     // Handle special cases where numerator or denominator is 0
1401     if (num.is_zero())
1402         return _ex0();
1403     if (den.expand().is_zero())
1404         throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
1405
1406     // More special cases
1407     if (is_ex_exactly_of_type(den, numeric))
1408         return num / den;
1409
1410     // Bring numerator and denominator to Z[X] by multiplying with
1411     // LCM of all coefficients' denominators
1412     ex num_lcm = lcm_of_coefficients_denominators(num);
1413     ex den_lcm = lcm_of_coefficients_denominators(den);
1414         num = multiply_lcm(num, num_lcm);
1415         den = multiply_lcm(den, den_lcm);
1416     pre_factor = den_lcm / num_lcm;
1417
1418     // Cancel GCD from numerator and denominator
1419     ex cnum, cden;
1420     if (gcd(num, den, &cnum, &cden, false) != _ex1()) {
1421                 num = cnum;
1422                 den = cden;
1423         }
1424
1425         // Make denominator unit normal (i.e. coefficient of first symbol
1426         // as defined by get_first_symbol() is made positive)
1427         const symbol *x;
1428         if (get_first_symbol(den, x)) {
1429                 if (den.unit(*x).compare(_ex0()) < 0) {
1430                         num *= _ex_1();
1431                         den *= _ex_1();
1432                 }
1433         }
1434     return pre_factor * num / den;
1435 }
1436
1437
1438 /** Implementation of ex::normal() for a sum. It expands terms and performs
1439  *  fractional addition.
1440  *  @see ex::normal */
1441 ex add::normal(lst &sym_lst, lst &repl_lst, int level) const
1442 {
1443     // Normalize and expand children
1444     exvector o;
1445     o.reserve(seq.size()+1);
1446     epvector::const_iterator it = seq.begin(), itend = seq.end();
1447     while (it != itend) {
1448         ex n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1).expand();
1449         if (is_ex_exactly_of_type(n, add)) {
1450             epvector::const_iterator bit = (static_cast<add *>(n.bp))->seq.begin(), bitend = (static_cast<add *>(n.bp))->seq.end();
1451             while (bit != bitend) {
1452                 o.push_back(recombine_pair_to_ex(*bit));
1453                 bit++;
1454             }
1455             o.push_back((static_cast<add *>(n.bp))->overall_coeff);
1456         } else
1457             o.push_back(n);
1458         it++;
1459     }
1460     o.push_back(overall_coeff.bp->normal(sym_lst, repl_lst, level-1));
1461
1462     // Determine common denominator
1463     ex den = _ex1();
1464     exvector::const_iterator ait = o.begin(), aitend = o.end();
1465     while (ait != aitend) {
1466         den = lcm((*ait).denom(false), den, false);
1467         ait++;
1468     }
1469
1470     // Add fractions
1471     if (den.is_equal(_ex1()))
1472         return (new add(o))->setflag(status_flags::dynallocated);
1473     else {
1474         exvector num_seq;
1475         for (ait=o.begin(); ait!=aitend; ait++) {
1476             ex q;
1477             if (!divide(den, (*ait).denom(false), q, false)) {
1478                 // should not happen
1479                 throw(std::runtime_error("invalid expression in add::normal, division failed"));
1480             }
1481             num_seq.push_back((*ait).numer(false) * q);
1482         }
1483         ex num = add(num_seq);
1484
1485         // Cancel common factors from num/den
1486         return frac_cancel(num, den);
1487     }
1488 }
1489
1490
1491 /** Implementation of ex::normal() for a product. It cancels common factors
1492  *  from fractions.
1493  *  @see ex::normal() */
1494 ex mul::normal(lst &sym_lst, lst &repl_lst, int level) const
1495 {
1496     // Normalize children
1497     exvector o;
1498     o.reserve(seq.size()+1);
1499     epvector::const_iterator it = seq.begin(), itend = seq.end();
1500     while (it != itend) {
1501         o.push_back(recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1));
1502         it++;
1503     }
1504     o.push_back(overall_coeff.bp->normal(sym_lst, repl_lst, level-1));
1505     ex n = (new mul(o))->setflag(status_flags::dynallocated);
1506     return frac_cancel(n.numer(false), n.denom(false));
1507 }
1508
1509
1510 /** Implementation of ex::normal() for powers. It normalizes the basis,
1511  *  distributes integer exponents to numerator and denominator, and replaces
1512  *  non-integer powers by temporary symbols.
1513  *  @see ex::normal */
1514 ex power::normal(lst &sym_lst, lst &repl_lst, int level) const
1515 {
1516     if (exponent.info(info_flags::integer)) {
1517         // Integer powers are distributed
1518         ex n = basis.bp->normal(sym_lst, repl_lst, level-1);
1519         ex num = n.numer(false);
1520         ex den = n.denom(false);
1521         return power(num, exponent) / power(den, exponent);
1522     } else {
1523         // Non-integer powers are replaced by temporary symbol (after normalizing basis)
1524         ex n = power(basis.bp->normal(sym_lst, repl_lst, level-1), exponent);
1525         return replace_with_symbol(n, sym_lst, repl_lst);
1526     }
1527 }
1528
1529
1530 /** Implementation of ex::normal() for pseries. It normalizes each coefficient and
1531  *  replaces the series by a temporary symbol.
1532  *  @see ex::normal */
1533 ex pseries::normal(lst &sym_lst, lst &repl_lst, int level) const
1534 {
1535     epvector new_seq;
1536     new_seq.reserve(seq.size());
1537
1538     epvector::const_iterator it = seq.begin(), itend = seq.end();
1539     while (it != itend) {
1540         new_seq.push_back(expair(it->rest.normal(), it->coeff));
1541         it++;
1542     }
1543
1544     ex n = pseries(var, point, new_seq);
1545     return replace_with_symbol(n, sym_lst, repl_lst);
1546 }
1547
1548
1549 /** Normalization of rational functions.
1550  *  This function converts an expression to its normal form
1551  *  "numerator/denominator", where numerator and denominator are (relatively
1552  *  prime) polynomials. Any subexpressions which are not rational functions
1553  *  (like non-rational numbers, non-integer powers or functions like Sin(),
1554  *  Cos() etc.) are replaced by temporary symbols which are re-substituted by
1555  *  the (normalized) subexpressions before normal() returns (this way, any
1556  *  expression can be treated as a rational function). normal() is applied
1557  *  recursively to arguments of functions etc.
1558  *
1559  *  @param level maximum depth of recursion
1560  *  @return normalized expression */
1561 ex ex::normal(int level) const
1562 {
1563     lst sym_lst, repl_lst;
1564     ex e = bp->normal(sym_lst, repl_lst, level);
1565     if (sym_lst.nops() > 0)
1566         return e.subs(sym_lst, repl_lst);
1567     else
1568         return e;
1569 }
1570
1571 #ifndef NO_NAMESPACE_GINAC
1572 } // namespace GiNaC
1573 #endif // ndef NO_NAMESPACE_GINAC