58913a8bcfd1a786f377c2b667e1cc0be4209292
[ginac.git] / ginac / power.cpp
1 /** @file power.cpp
2  *
3  *  Implementation of GiNaC's symbolic exponentiation (basis^exponent). */
4
5 /*
6  *  GiNaC Copyright (C) 1999-2001 Johannes Gutenberg University Mainz, Germany
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 2 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, write to the Free Software
20  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 #include <vector>
24 #include <iostream>
25 #include <stdexcept>
26
27 #include "power.h"
28 #include "expairseq.h"
29 #include "add.h"
30 #include "mul.h"
31 #include "ncmul.h"
32 #include "numeric.h"
33 #include "constant.h"
34 #include "inifcns.h" // for log() in power::derivative()
35 #include "matrix.h"
36 #include "symbol.h"
37 #include "print.h"
38 #include "archive.h"
39 #include "utils.h"
40
41 namespace GiNaC {
42
43 GINAC_IMPLEMENT_REGISTERED_CLASS(power, basic)
44
45 typedef std::vector<int> intvector;
46
47 //////////
48 // default ctor, dtor, copy ctor, assignment operator and helpers
49 //////////
50
51 power::power() : inherited(TINFO_power) { }
52
53 void power::copy(const power & other)
54 {
55         inherited::copy(other);
56         basis = other.basis;
57         exponent = other.exponent;
58 }
59
60 DEFAULT_DESTROY(power)
61
62 //////////
63 // other ctors
64 //////////
65
66 // all inlined
67
68 //////////
69 // archiving
70 //////////
71
72 power::power(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
73 {
74         n.find_ex("basis", basis, sym_lst);
75         n.find_ex("exponent", exponent, sym_lst);
76 }
77
78 void power::archive(archive_node &n) const
79 {
80         inherited::archive(n);
81         n.add_ex("basis", basis);
82         n.add_ex("exponent", exponent);
83 }
84
85 DEFAULT_UNARCHIVE(power)
86
87 //////////
88 // functions overriding virtual functions from base classes
89 //////////
90
91 // public
92
93 static void print_sym_pow(const print_context & c, const symbol &x, int exp)
94 {
95         // Optimal output of integer powers of symbols to aid compiler CSE.
96         // C.f. ISO/IEC 14882:1998, section 1.9 [intro execution], paragraph 15
97         // to learn why such a parenthisation is really necessary.
98         if (exp == 1) {
99                 x.print(c);
100         } else if (exp == 2) {
101                 x.print(c);
102                 c.s << "*";
103                 x.print(c);
104         } else if (exp & 1) {
105                 x.print(c);
106                 c.s << "*";
107                 print_sym_pow(c, x, exp-1);
108         } else {
109                 c.s << "(";
110                 print_sym_pow(c, x, exp >> 1);
111                 c.s << ")*(";
112                 print_sym_pow(c, x, exp >> 1);
113                 c.s << ")";
114         }
115 }
116
117 void power::print(const print_context & c, unsigned level) const
118 {
119         if (is_a<print_tree>(c)) {
120
121                 inherited::print(c, level);
122
123         } else if (is_a<print_csrc>(c)) {
124
125                 // Integer powers of symbols are printed in a special, optimized way
126                 if (exponent.info(info_flags::integer)
127                  && (is_exactly_a<symbol>(basis) || is_exactly_a<constant>(basis))) {
128                         int exp = ex_to<numeric>(exponent).to_int();
129                         if (exp > 0)
130                                 c.s << '(';
131                         else {
132                                 exp = -exp;
133                                 if (is_a<print_csrc_cl_N>(c))
134                                         c.s << "recip(";
135                                 else
136                                         c.s << "1.0/(";
137                         }
138                         print_sym_pow(c, ex_to<symbol>(basis), exp);
139                         c.s << ')';
140
141                 // <expr>^-1 is printed as "1.0/<expr>" or with the recip() function of CLN
142                 } else if (exponent.compare(_num_1) == 0) {
143                         if (is_a<print_csrc_cl_N>(c))
144                                 c.s << "recip(";
145                         else
146                                 c.s << "1.0/(";
147                         basis.print(c);
148                         c.s << ')';
149
150                 // Otherwise, use the pow() or expt() (CLN) functions
151                 } else {
152                         if (is_a<print_csrc_cl_N>(c))
153                                 c.s << "expt(";
154                         else
155                                 c.s << "pow(";
156                         basis.print(c);
157                         c.s << ',';
158                         exponent.print(c);
159                         c.s << ')';
160                 }
161
162         } else {
163
164                 if (exponent.is_equal(_ex1_2)) {
165                         if (is_a<print_latex>(c))
166                                 c.s << "\\sqrt{";
167                         else
168                                 c.s << "sqrt(";
169                         basis.print(c);
170                         if (is_a<print_latex>(c))
171                                 c.s << '}';
172                         else
173                                 c.s << ')';
174                 } else {
175                         if (precedence() <= level) {
176                                 if (is_a<print_latex>(c))
177                                         c.s << "{(";
178                                 else
179                                         c.s << "(";
180                         }
181                         basis.print(c, precedence());
182                         c.s << '^';
183                         if (is_a<print_latex>(c))
184                                 c.s << '{';
185                         exponent.print(c, precedence());
186                         if (is_a<print_latex>(c))
187                                 c.s << '}';
188                         if (precedence() <= level) {
189                                 if (is_a<print_latex>(c))
190                                         c.s << ")}";
191                                 else
192                                         c.s << ')';
193                         }
194                 }
195         }
196 }
197
198 bool power::info(unsigned inf) const
199 {
200         switch (inf) {
201                 case info_flags::polynomial:
202                 case info_flags::integer_polynomial:
203                 case info_flags::cinteger_polynomial:
204                 case info_flags::rational_polynomial:
205                 case info_flags::crational_polynomial:
206                         return exponent.info(info_flags::nonnegint);
207                 case info_flags::rational_function:
208                         return exponent.info(info_flags::integer);
209                 case info_flags::algebraic:
210                         return (!exponent.info(info_flags::integer) ||
211                                         basis.info(inf));
212         }
213         return inherited::info(inf);
214 }
215
216 unsigned power::nops() const
217 {
218         return 2;
219 }
220
221 ex & power::let_op(int i)
222 {
223         GINAC_ASSERT(i>=0);
224         GINAC_ASSERT(i<2);
225
226         return i==0 ? basis : exponent;
227 }
228
229 ex power::map(map_function & f) const
230 {
231         return (new power(f(basis), f(exponent)))->setflag(status_flags::dynallocated);
232 }
233
234 int power::degree(const ex & s) const
235 {
236         if (is_ex_exactly_of_type(exponent, numeric) && ex_to<numeric>(exponent).is_integer()) {
237                 if (basis.is_equal(s))
238                         return ex_to<numeric>(exponent).to_int();
239                 else
240                         return basis.degree(s) * ex_to<numeric>(exponent).to_int();
241         }
242         return 0;
243 }
244
245 int power::ldegree(const ex & s) const 
246 {
247         if (is_ex_exactly_of_type(exponent, numeric) && ex_to<numeric>(exponent).is_integer()) {
248                 if (basis.is_equal(s))
249                         return ex_to<numeric>(exponent).to_int();
250                 else
251                         return basis.ldegree(s) * ex_to<numeric>(exponent).to_int();
252         }
253         return 0;
254 }
255
256 ex power::coeff(const ex & s, int n) const
257 {
258         if (!basis.is_equal(s)) {
259                 // basis not equal to s
260                 if (n == 0)
261                         return *this;
262                 else
263                         return _ex0;
264         } else {
265                 // basis equal to s
266                 if (is_ex_exactly_of_type(exponent, numeric) && ex_to<numeric>(exponent).is_integer()) {
267                         // integer exponent
268                         int int_exp = ex_to<numeric>(exponent).to_int();
269                         if (n == int_exp)
270                                 return _ex1;
271                         else
272                                 return _ex0;
273                 } else {
274                         // non-integer exponents are treated as zero
275                         if (n == 0)
276                                 return *this;
277                         else
278                                 return _ex0;
279                 }
280         }
281 }
282
283 /** Perform automatic term rewriting rules in this class.  In the following
284  *  x, x1, x2,... stand for a symbolic variables of type ex and c, c1, c2...
285  *  stand for such expressions that contain a plain number.
286  *  - ^(x,0) -> 1  (also handles ^(0,0))
287  *  - ^(x,1) -> x
288  *  - ^(0,c) -> 0 or exception  (depending on the real part of c)
289  *  - ^(1,x) -> 1
290  *  - ^(c1,c2) -> *(c1^n,c1^(c2-n))  (so that 0<(c2-n)<1, try to evaluate roots, possibly in numerator and denominator of c1)
291  *  - ^(^(x,c1),c2) -> ^(x,c1*c2)  (c2 integer or -1 < c1 <= 1, case c1=1 should not happen, see below!)
292  *  - ^(*(x,y,z),c) -> *(x^c,y^c,z^c)  (if c integer)
293  *  - ^(*(x,c1),c2) -> ^(x,c2)*c1^c2  (c1>0)
294  *  - ^(*(x,c1),c2) -> ^(-x,c2)*c1^c2  (c1<0)
295  *
296  *  @param level cut-off in recursive evaluation */
297 ex power::eval(int level) const
298 {
299         if ((level==1) && (flags & status_flags::evaluated))
300                 return *this;
301         else if (level == -max_recursion_level)
302                 throw(std::runtime_error("max recursion level reached"));
303         
304         const ex & ebasis    = level==1 ? basis    : basis.eval(level-1);
305         const ex & eexponent = level==1 ? exponent : exponent.eval(level-1);
306         
307         bool basis_is_numerical = false;
308         bool exponent_is_numerical = false;
309         const numeric *num_basis;
310         const numeric *num_exponent;
311         
312         if (is_ex_exactly_of_type(ebasis, numeric)) {
313                 basis_is_numerical = true;
314                 num_basis = &ex_to<numeric>(ebasis);
315         }
316         if (is_ex_exactly_of_type(eexponent, numeric)) {
317                 exponent_is_numerical = true;
318                 num_exponent = &ex_to<numeric>(eexponent);
319         }
320         
321         // ^(x,0) -> 1  (0^0 also handled here)
322         if (eexponent.is_zero()) {
323                 if (ebasis.is_zero())
324                         throw (std::domain_error("power::eval(): pow(0,0) is undefined"));
325                 else
326                         return _ex1;
327         }
328         
329         // ^(x,1) -> x
330         if (eexponent.is_equal(_ex1))
331                 return ebasis;
332
333         // ^(0,c1) -> 0 or exception  (depending on real value of c1)
334         if (ebasis.is_zero() && exponent_is_numerical) {
335                 if ((num_exponent->real()).is_zero())
336                         throw (std::domain_error("power::eval(): pow(0,I) is undefined"));
337                 else if ((num_exponent->real()).is_negative())
338                         throw (pole_error("power::eval(): division by zero",1));
339                 else
340                         return _ex0;
341         }
342
343         // ^(1,x) -> 1
344         if (ebasis.is_equal(_ex1))
345                 return _ex1;
346
347         if (exponent_is_numerical) {
348
349                 // ^(c1,c2) -> c1^c2  (c1, c2 numeric(),
350                 // except if c1,c2 are rational, but c1^c2 is not)
351                 if (basis_is_numerical) {
352                         const bool basis_is_crational = num_basis->is_crational();
353                         const bool exponent_is_crational = num_exponent->is_crational();
354                         if (!basis_is_crational || !exponent_is_crational) {
355                                 // return a plain float
356                                 return (new numeric(num_basis->power(*num_exponent)))->setflag(status_flags::dynallocated |
357                                                                                                status_flags::evaluated |
358                                                                                                status_flags::expanded);
359                         }
360
361                         const numeric res = num_basis->power(*num_exponent);
362                         if (res.is_crational()) {
363                                 return res;
364                         }
365                         GINAC_ASSERT(!num_exponent->is_integer());  // has been handled by now
366
367                         // ^(c1,n/m) -> *(c1^q,c1^(n/m-q)), 0<(n/m-q)<1, q integer
368                         if (basis_is_crational && exponent_is_crational
369                             && num_exponent->is_real()
370                             && !num_exponent->is_integer()) {
371                                 const numeric n = num_exponent->numer();
372                                 const numeric m = num_exponent->denom();
373                                 numeric r;
374                                 numeric q = iquo(n, m, r);
375                                 if (r.is_negative()) {
376                                         r += m;
377                                         --q;
378                                 }
379                                 if (q.is_zero()) {  // the exponent was in the allowed range 0<(n/m)<1
380                                         if (num_basis->is_rational() && !num_basis->is_integer()) {
381                                                 // try it for numerator and denominator separately, in order to
382                                                 // partially simplify things like (5/8)^(1/3) -> 1/2*5^(1/3)
383                                                 const numeric bnum = num_basis->numer();
384                                                 const numeric bden = num_basis->denom();
385                                                 const numeric res_bnum = bnum.power(*num_exponent);
386                                                 const numeric res_bden = bden.power(*num_exponent);
387                                                 if (res_bnum.is_integer())
388                                                         return (new mul(power(bden,-*num_exponent),res_bnum))->setflag(status_flags::dynallocated | status_flags::evaluated);
389                                                 if (res_bden.is_integer())
390                                                         return (new mul(power(bnum,*num_exponent),res_bden.inverse()))->setflag(status_flags::dynallocated | status_flags::evaluated);
391                                         }
392                                         return this->hold();
393                                 } else {
394                                         // assemble resulting product, but allowing for a re-evaluation,
395                                         // because otherwise we'll end up with something like
396                                         //    (7/8)^(4/3)  ->  7/8*(1/2*7^(1/3))
397                                         // instead of 7/16*7^(1/3).
398                                         ex prod = power(*num_basis,r.div(m));
399                                         return prod*power(*num_basis,q);
400                                 }
401                         }
402                 }
403         
404                 // ^(^(x,c1),c2) -> ^(x,c1*c2)
405                 // (c1, c2 numeric(), c2 integer or -1 < c1 <= 1,
406                 // case c1==1 should not happen, see below!)
407                 if (is_ex_exactly_of_type(ebasis,power)) {
408                         const power & sub_power = ex_to<power>(ebasis);
409                         const ex & sub_basis = sub_power.basis;
410                         const ex & sub_exponent = sub_power.exponent;
411                         if (is_ex_exactly_of_type(sub_exponent,numeric)) {
412                                 const numeric & num_sub_exponent = ex_to<numeric>(sub_exponent);
413                                 GINAC_ASSERT(num_sub_exponent!=numeric(1));
414                                 if (num_exponent->is_integer() || (abs(num_sub_exponent) - _num1).is_negative())
415                                         return power(sub_basis,num_sub_exponent.mul(*num_exponent));
416                         }
417                 }
418         
419                 // ^(*(x,y,z),c1) -> *(x^c1,y^c1,z^c1) (c1 integer)
420                 if (num_exponent->is_integer() && is_ex_exactly_of_type(ebasis,mul)) {
421                         return expand_mul(ex_to<mul>(ebasis), *num_exponent);
422                 }
423         
424                 // ^(*(...,x;c1),c2) -> *(^(*(...,x;1),c2),c1^c2)  (c1, c2 numeric(), c1>0)
425                 // ^(*(...,x;c1),c2) -> *(^(*(...,x;-1),c2),(-c1)^c2)  (c1, c2 numeric(), c1<0)
426                 if (is_ex_exactly_of_type(ebasis,mul)) {
427                         GINAC_ASSERT(!num_exponent->is_integer()); // should have been handled above
428                         const mul & mulref = ex_to<mul>(ebasis);
429                         if (!mulref.overall_coeff.is_equal(_ex1)) {
430                                 const numeric & num_coeff = ex_to<numeric>(mulref.overall_coeff);
431                                 if (num_coeff.is_real()) {
432                                         if (num_coeff.is_positive()) {
433                                                 mul *mulp = new mul(mulref);
434                                                 mulp->overall_coeff = _ex1;
435                                                 mulp->clearflag(status_flags::evaluated);
436                                                 mulp->clearflag(status_flags::hash_calculated);
437                                                 return (new mul(power(*mulp,exponent),
438                                                                 power(num_coeff,*num_exponent)))->setflag(status_flags::dynallocated);
439                                         } else {
440                                                 GINAC_ASSERT(num_coeff.compare(_num0)<0);
441                                                 if (!num_coeff.is_equal(_num_1)) {
442                                                         mul *mulp = new mul(mulref);
443                                                         mulp->overall_coeff = _ex_1;
444                                                         mulp->clearflag(status_flags::evaluated);
445                                                         mulp->clearflag(status_flags::hash_calculated);
446                                                         return (new mul(power(*mulp,exponent),
447                                                                         power(abs(num_coeff),*num_exponent)))->setflag(status_flags::dynallocated);
448                                                 }
449                                         }
450                                 }
451                         }
452                 }
453
454                 // ^(nc,c1) -> ncmul(nc,nc,...) (c1 positive integer, unless nc is a matrix)
455                 if (num_exponent->is_pos_integer() &&
456                     ebasis.return_type() != return_types::commutative &&
457                     !is_ex_of_type(ebasis,matrix)) {
458                         return ncmul(exvector(num_exponent->to_int(), ebasis), true);
459                 }
460         }
461         
462         if (are_ex_trivially_equal(ebasis,basis) &&
463             are_ex_trivially_equal(eexponent,exponent)) {
464                 return this->hold();
465         }
466         return (new power(ebasis, eexponent))->setflag(status_flags::dynallocated |
467                                                        status_flags::evaluated);
468 }
469
470 ex power::evalf(int level) const
471 {
472         ex ebasis;
473         ex eexponent;
474         
475         if (level==1) {
476                 ebasis = basis;
477                 eexponent = exponent;
478         } else if (level == -max_recursion_level) {
479                 throw(std::runtime_error("max recursion level reached"));
480         } else {
481                 ebasis = basis.evalf(level-1);
482                 if (!is_exactly_a<numeric>(exponent))
483                         eexponent = exponent.evalf(level-1);
484                 else
485                         eexponent = exponent;
486         }
487
488         return power(ebasis,eexponent);
489 }
490
491 ex power::evalm(void) const
492 {
493         const ex ebasis = basis.evalm();
494         const ex eexponent = exponent.evalm();
495         if (is_ex_of_type(ebasis,matrix)) {
496                 if (is_ex_of_type(eexponent,numeric)) {
497                         return (new matrix(ex_to<matrix>(ebasis).pow(eexponent)))->setflag(status_flags::dynallocated);
498                 }
499         }
500         return (new power(ebasis, eexponent))->setflag(status_flags::dynallocated);
501 }
502
503 ex power::subs(const lst & ls, const lst & lr, bool no_pattern) const
504 {
505         const ex &subsed_basis = basis.subs(ls, lr, no_pattern);
506         const ex &subsed_exponent = exponent.subs(ls, lr, no_pattern);
507
508         if (are_ex_trivially_equal(basis, subsed_basis)
509          && are_ex_trivially_equal(exponent, subsed_exponent))
510                 return basic::subs(ls, lr, no_pattern);
511         else
512                 return power(subsed_basis, subsed_exponent).basic::subs(ls, lr, no_pattern);
513 }
514
515 ex power::simplify_ncmul(const exvector & v) const
516 {
517         return inherited::simplify_ncmul(v);
518 }
519
520 // protected
521
522 /** Implementation of ex::diff() for a power.
523  *  @see ex::diff */
524 ex power::derivative(const symbol & s) const
525 {
526         if (exponent.info(info_flags::real)) {
527                 // D(b^r) = r * b^(r-1) * D(b) (faster than the formula below)
528                 epvector newseq;
529                 newseq.reserve(2);
530                 newseq.push_back(expair(basis, exponent - _ex1));
531                 newseq.push_back(expair(basis.diff(s), _ex1));
532                 return mul(newseq, exponent);
533         } else {
534                 // D(b^e) = b^e * (D(e)*ln(b) + e*D(b)/b)
535                 return mul(*this,
536                            add(mul(exponent.diff(s), log(basis)),
537                            mul(mul(exponent, basis.diff(s)), power(basis, _ex_1))));
538         }
539 }
540
541 int power::compare_same_type(const basic & other) const
542 {
543         GINAC_ASSERT(is_exactly_a<power>(other));
544         const power &o = static_cast<const power &>(other);
545
546         int cmpval = basis.compare(o.basis);
547         if (cmpval)
548                 return cmpval;
549         else
550                 return exponent.compare(o.exponent);
551 }
552
553 unsigned power::return_type(void) const
554 {
555         return basis.return_type();
556 }
557    
558 unsigned power::return_type_tinfo(void) const
559 {
560         return basis.return_type_tinfo();
561 }
562
563 ex power::expand(unsigned options) const
564 {
565         if (options == 0 && (flags & status_flags::expanded))
566                 return *this;
567         
568         const ex expanded_basis = basis.expand(options);
569         const ex expanded_exponent = exponent.expand(options);
570         
571         // x^(a+b) -> x^a * x^b
572         if (is_ex_exactly_of_type(expanded_exponent, add)) {
573                 const add &a = ex_to<add>(expanded_exponent);
574                 exvector distrseq;
575                 distrseq.reserve(a.seq.size() + 1);
576                 epvector::const_iterator last = a.seq.end();
577                 epvector::const_iterator cit = a.seq.begin();
578                 while (cit!=last) {
579                         distrseq.push_back(power(expanded_basis, a.recombine_pair_to_ex(*cit)));
580                         ++cit;
581                 }
582                 
583                 // Make sure that e.g. (x+y)^(2+a) expands the (x+y)^2 factor
584                 if (ex_to<numeric>(a.overall_coeff).is_integer()) {
585                         const numeric &num_exponent = ex_to<numeric>(a.overall_coeff);
586                         int int_exponent = num_exponent.to_int();
587                         if (int_exponent > 0 && is_ex_exactly_of_type(expanded_basis, add))
588                                 distrseq.push_back(expand_add(ex_to<add>(expanded_basis), int_exponent));
589                         else
590                                 distrseq.push_back(power(expanded_basis, a.overall_coeff));
591                 } else
592                         distrseq.push_back(power(expanded_basis, a.overall_coeff));
593                 
594                 // Make sure that e.g. (x+y)^(1+a) -> x*(x+y)^a + y*(x+y)^a
595                 ex r = (new mul(distrseq))->setflag(status_flags::dynallocated);
596                 return r.expand();
597         }
598         
599         if (!is_ex_exactly_of_type(expanded_exponent, numeric) ||
600                 !ex_to<numeric>(expanded_exponent).is_integer()) {
601                 if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent)) {
602                         return this->hold();
603                 } else {
604                         return (new power(expanded_basis,expanded_exponent))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
605                 }
606         }
607         
608         // integer numeric exponent
609         const numeric & num_exponent = ex_to<numeric>(expanded_exponent);
610         int int_exponent = num_exponent.to_int();
611         
612         // (x+y)^n, n>0
613         if (int_exponent > 0 && is_ex_exactly_of_type(expanded_basis,add))
614                 return expand_add(ex_to<add>(expanded_basis), int_exponent);
615         
616         // (x*y)^n -> x^n * y^n
617         if (is_ex_exactly_of_type(expanded_basis,mul))
618                 return expand_mul(ex_to<mul>(expanded_basis), num_exponent);
619         
620         // cannot expand further
621         if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent))
622                 return this->hold();
623         else
624                 return (new power(expanded_basis,expanded_exponent))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
625 }
626
627 //////////
628 // new virtual functions which can be overridden by derived classes
629 //////////
630
631 // none
632
633 //////////
634 // non-virtual functions in this class
635 //////////
636
637 /** expand a^n where a is an add and n is an integer.
638  *  @see power::expand */
639 ex power::expand_add(const add & a, int n) const
640 {
641         if (n==2)
642                 return expand_add_2(a);
643         
644         int m = a.nops();
645         exvector sum;
646         sum.reserve((n+1)*(m-1));
647         intvector k(m-1);
648         intvector k_cum(m-1); // k_cum[l]:=sum(i=0,l,k[l]);
649         intvector upper_limit(m-1);
650         int l;
651         
652         for (int l=0; l<m-1; l++) {
653                 k[l] = 0;
654                 k_cum[l] = 0;
655                 upper_limit[l] = n;
656         }
657         
658         while (true) {
659                 exvector term;
660                 term.reserve(m+1);
661                 for (l=0; l<m-1; l++) {
662                         const ex & b = a.op(l);
663                         GINAC_ASSERT(!is_exactly_a<add>(b));
664                         GINAC_ASSERT(!is_exactly_a<power>(b) ||
665                                      !is_exactly_a<numeric>(ex_to<power>(b).exponent) ||
666                                      !ex_to<numeric>(ex_to<power>(b).exponent).is_pos_integer() ||
667                                      !is_exactly_a<add>(ex_to<power>(b).basis) ||
668                                      !is_exactly_a<mul>(ex_to<power>(b).basis) ||
669                                      !is_exactly_a<power>(ex_to<power>(b).basis));
670                         if (is_ex_exactly_of_type(b,mul))
671                                 term.push_back(expand_mul(ex_to<mul>(b),numeric(k[l])));
672                         else
673                                 term.push_back(power(b,k[l]));
674                 }
675                 
676                 const ex & b = a.op(l);
677                 GINAC_ASSERT(!is_exactly_a<add>(b));
678                 GINAC_ASSERT(!is_exactly_a<power>(b) ||
679                              !is_exactly_a<numeric>(ex_to<power>(b).exponent) ||
680                              !ex_to<numeric>(ex_to<power>(b).exponent).is_pos_integer() ||
681                              !is_exactly_a<add>(ex_to<power>(b).basis) ||
682                              !is_exactly_a<mul>(ex_to<power>(b).basis) ||
683                              !is_exactly_a<power>(ex_to<power>(b).basis));
684                 if (is_ex_exactly_of_type(b,mul))
685                         term.push_back(expand_mul(ex_to<mul>(b),numeric(n-k_cum[m-2])));
686                 else
687                         term.push_back(power(b,n-k_cum[m-2]));
688                 
689                 numeric f = binomial(numeric(n),numeric(k[0]));
690                 for (l=1; l<m-1; l++)
691                         f *= binomial(numeric(n-k_cum[l-1]),numeric(k[l]));
692                 
693                 term.push_back(f);
694                 
695                 // TODO: Can we optimize this?  Alex seemed to think so...
696                 sum.push_back((new mul(term))->setflag(status_flags::dynallocated));
697                 
698                 // increment k[]
699                 l = m-2;
700                 while ((l>=0) && ((++k[l])>upper_limit[l])) {
701                         k[l] = 0;    
702                         --l;
703                 }
704                 if (l<0) break;
705                 
706                 // recalc k_cum[] and upper_limit[]
707                 if (l==0)
708                         k_cum[0] = k[0];
709                 else
710                         k_cum[l] = k_cum[l-1]+k[l];
711                 
712                 for (int i=l+1; i<m-1; i++)
713                         k_cum[i] = k_cum[i-1]+k[i];
714                 
715                 for (int i=l+1; i<m-1; i++)
716                         upper_limit[i] = n-k_cum[i-1];
717         }
718         return (new add(sum))->setflag(status_flags::dynallocated |
719                                        status_flags::expanded );
720 }
721
722
723 /** Special case of power::expand_add. Expands a^2 where a is an add.
724  *  @see power::expand_add */
725 ex power::expand_add_2(const add & a) const
726 {
727         epvector sum;
728         unsigned a_nops = a.nops();
729         sum.reserve((a_nops*(a_nops+1))/2);
730         epvector::const_iterator last = a.seq.end();
731         
732         // power(+(x,...,z;c),2)=power(+(x,...,z;0),2)+2*c*+(x,...,z;0)+c*c
733         // first part: ignore overall_coeff and expand other terms
734         for (epvector::const_iterator cit0=a.seq.begin(); cit0!=last; ++cit0) {
735                 const ex & r = cit0->rest;
736                 const ex & c = cit0->coeff;
737                 
738                 GINAC_ASSERT(!is_exactly_a<add>(r));
739                 GINAC_ASSERT(!is_exactly_a<power>(r) ||
740                              !is_exactly_a<numeric>(ex_to<power>(r).exponent) ||
741                              !ex_to<numeric>(ex_to<power>(r).exponent).is_pos_integer() ||
742                              !is_exactly_a<add>(ex_to<power>(r).basis) ||
743                              !is_exactly_a<mul>(ex_to<power>(r).basis) ||
744                              !is_exactly_a<power>(ex_to<power>(r).basis));
745                 
746                 if (are_ex_trivially_equal(c,_ex1)) {
747                         if (is_ex_exactly_of_type(r,mul)) {
748                                 sum.push_back(expair(expand_mul(ex_to<mul>(r),_num2),
749                                                      _ex1));
750                         } else {
751                                 sum.push_back(expair((new power(r,_ex2))->setflag(status_flags::dynallocated),
752                                                      _ex1));
753                         }
754                 } else {
755                         if (is_ex_exactly_of_type(r,mul)) {
756                                 sum.push_back(expair(expand_mul(ex_to<mul>(r),_num2),
757                                                      ex_to<numeric>(c).power_dyn(_num2)));
758                         } else {
759                                 sum.push_back(expair((new power(r,_ex2))->setflag(status_flags::dynallocated),
760                                                      ex_to<numeric>(c).power_dyn(_num2)));
761                         }
762                 }
763                         
764                 for (epvector::const_iterator cit1=cit0+1; cit1!=last; ++cit1) {
765                         const ex & r1 = cit1->rest;
766                         const ex & c1 = cit1->coeff;
767                         sum.push_back(a.combine_ex_with_coeff_to_pair((new mul(r,r1))->setflag(status_flags::dynallocated),
768                                                                       _num2.mul(ex_to<numeric>(c)).mul_dyn(ex_to<numeric>(c1))));
769                 }
770         }
771         
772         GINAC_ASSERT(sum.size()==(a.seq.size()*(a.seq.size()+1))/2);
773         
774         // second part: add terms coming from overall_factor (if != 0)
775         if (!a.overall_coeff.is_zero()) {
776                 epvector::const_iterator i = a.seq.begin(), end = a.seq.end();
777                 while (i != end) {
778                         sum.push_back(a.combine_pair_with_coeff_to_pair(*i, ex_to<numeric>(a.overall_coeff).mul_dyn(_num2)));
779                         ++i;
780                 }
781                 sum.push_back(expair(ex_to<numeric>(a.overall_coeff).power_dyn(_num2),_ex1));
782         }
783         
784         GINAC_ASSERT(sum.size()==(a_nops*(a_nops+1))/2);
785         
786         return (new add(sum))->setflag(status_flags::dynallocated | status_flags::expanded);
787 }
788
789 /** Expand factors of m in m^n where m is a mul and n is and integer
790  *  @see power::expand */
791 ex power::expand_mul(const mul & m, const numeric & n) const
792 {
793         if (n.is_zero())
794                 return _ex1;
795         
796         epvector distrseq;
797         distrseq.reserve(m.seq.size());
798         epvector::const_iterator last = m.seq.end();
799         epvector::const_iterator cit = m.seq.begin();
800         while (cit!=last) {
801                 if (is_ex_exactly_of_type((*cit).rest,numeric)) {
802                         distrseq.push_back(m.combine_pair_with_coeff_to_pair(*cit,n));
803                 } else {
804                         // it is safe not to call mul::combine_pair_with_coeff_to_pair()
805                         // since n is an integer
806                         distrseq.push_back(expair((*cit).rest, ex_to<numeric>((*cit).coeff).mul(n)));
807                 }
808                 ++cit;
809         }
810         return (new mul(distrseq,ex_to<numeric>(m.overall_coeff).power_dyn(n)))->setflag(status_flags::dynallocated);
811 }
812
813 } // namespace GiNaC