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