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