]> www.ginac.de Git - ginac.git/blob - ginac/power.cpp
Happy New Year!
[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-2016 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 "power.h"
24 #include "expairseq.h"
25 #include "add.h"
26 #include "mul.h"
27 #include "ncmul.h"
28 #include "numeric.h"
29 #include "constant.h"
30 #include "operators.h"
31 #include "inifcns.h" // for log() in power::derivative()
32 #include "matrix.h"
33 #include "indexed.h"
34 #include "symbol.h"
35 #include "lst.h"
36 #include "archive.h"
37 #include "utils.h"
38 #include "relational.h"
39 #include "compiler.h"
40
41 #include <iostream>
42 #include <limits>
43 #include <stdexcept>
44 #include <vector>
45 #include <algorithm>
46
47 namespace GiNaC {
48
49 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(power, basic,
50   print_func<print_dflt>(&power::do_print_dflt).
51   print_func<print_latex>(&power::do_print_latex).
52   print_func<print_csrc>(&power::do_print_csrc).
53   print_func<print_python>(&power::do_print_python).
54   print_func<print_python_repr>(&power::do_print_python_repr).
55   print_func<print_csrc_cl_N>(&power::do_print_csrc_cl_N))
56
57 //////////
58 // default constructor
59 //////////
60
61 power::power() { }
62
63 //////////
64 // other constructors
65 //////////
66
67 // all inlined
68
69 //////////
70 // archiving
71 //////////
72
73 void power::read_archive(const archive_node &n, lst &sym_lst)
74 {
75         inherited::read_archive(n, sym_lst);
76         n.find_ex("basis", basis, sym_lst);
77         n.find_ex("exponent", exponent, sym_lst);
78 }
79
80 void power::archive(archive_node &n) const
81 {
82         inherited::archive(n);
83         n.add_ex("basis", basis);
84         n.add_ex("exponent", exponent);
85 }
86
87 //////////
88 // functions overriding virtual functions from base classes
89 //////////
90
91 // public
92
93 void power::print_power(const print_context & c, const char *powersymbol, const char *openbrace, const char *closebrace, unsigned level) const
94 {
95         // Ordinary output of powers using '^' or '**'
96         if (precedence() <= level)
97                 c.s << openbrace << '(';
98         basis.print(c, precedence());
99         c.s << powersymbol;
100         c.s << openbrace;
101         exponent.print(c, precedence());
102         c.s << closebrace;
103         if (precedence() <= level)
104                 c.s << ')' << closebrace;
105 }
106
107 void power::do_print_dflt(const print_dflt & c, unsigned level) const
108 {
109         if (exponent.is_equal(_ex1_2)) {
110
111                 // Square roots are printed in a special way
112                 c.s << "sqrt(";
113                 basis.print(c);
114                 c.s << ')';
115
116         } else
117                 print_power(c, "^", "", "", level);
118 }
119
120 void power::do_print_latex(const print_latex & c, unsigned level) const
121 {
122         if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_negative()) {
123
124                 // Powers with negative numeric exponents are printed as fractions
125                 c.s << "\\frac{1}{";
126                 power(basis, -exponent).eval().print(c);
127                 c.s << '}';
128
129         } else if (exponent.is_equal(_ex1_2)) {
130
131                 // Square roots are printed in a special way
132                 c.s << "\\sqrt{";
133                 basis.print(c);
134                 c.s << '}';
135
136         } else
137                 print_power(c, "^", "{", "}", level);
138 }
139
140 static void print_sym_pow(const print_context & c, const symbol &x, int exp)
141 {
142         // Optimal output of integer powers of symbols to aid compiler CSE.
143         // C.f. ISO/IEC 14882:1998, section 1.9 [intro execution], paragraph 15
144         // to learn why such a parenthesation is really necessary.
145         if (exp == 1) {
146                 x.print(c);
147         } else if (exp == 2) {
148                 x.print(c);
149                 c.s << "*";
150                 x.print(c);
151         } else if (exp & 1) {
152                 x.print(c);
153                 c.s << "*";
154                 print_sym_pow(c, x, exp-1);
155         } else {
156                 c.s << "(";
157                 print_sym_pow(c, x, exp >> 1);
158                 c.s << ")*(";
159                 print_sym_pow(c, x, exp >> 1);
160                 c.s << ")";
161         }
162 }
163
164 void power::do_print_csrc_cl_N(const print_csrc_cl_N& c, unsigned level) const
165 {
166         if (exponent.is_equal(_ex_1)) {
167                 c.s << "recip(";
168                 basis.print(c);
169                 c.s << ')';
170                 return;
171         }
172         c.s << "expt(";
173         basis.print(c);
174         c.s << ", ";
175         exponent.print(c);
176         c.s << ')';
177 }
178
179 void power::do_print_csrc(const print_csrc & c, unsigned level) const
180 {
181         // Integer powers of symbols are printed in a special, optimized way
182         if (exponent.info(info_flags::integer) &&
183             (is_a<symbol>(basis) || is_a<constant>(basis))) {
184                 int exp = ex_to<numeric>(exponent).to_int();
185                 if (exp > 0)
186                         c.s << '(';
187                 else {
188                         exp = -exp;
189                         c.s << "1.0/(";
190                 }
191                 print_sym_pow(c, ex_to<symbol>(basis), exp);
192                 c.s << ')';
193
194         // <expr>^-1 is printed as "1.0/<expr>" or with the recip() function of CLN
195         } else if (exponent.is_equal(_ex_1)) {
196                 c.s << "1.0/(";
197                 basis.print(c);
198                 c.s << ')';
199
200         // Otherwise, use the pow() function
201         } else {
202                 c.s << "pow(";
203                 basis.print(c);
204                 c.s << ',';
205                 exponent.print(c);
206                 c.s << ')';
207         }
208 }
209
210 void power::do_print_python(const print_python & c, unsigned level) const
211 {
212         print_power(c, "**", "", "", level);
213 }
214
215 void power::do_print_python_repr(const print_python_repr & c, unsigned level) const
216 {
217         c.s << class_name() << '(';
218         basis.print(c);
219         c.s << ',';
220         exponent.print(c);
221         c.s << ')';
222 }
223
224 bool power::info(unsigned inf) const
225 {
226         switch (inf) {
227                 case info_flags::polynomial:
228                 case info_flags::integer_polynomial:
229                 case info_flags::cinteger_polynomial:
230                 case info_flags::rational_polynomial:
231                 case info_flags::crational_polynomial:
232                         return exponent.info(info_flags::nonnegint) &&
233                                basis.info(inf);
234                 case info_flags::rational_function:
235                         return exponent.info(info_flags::integer) &&
236                                basis.info(inf);
237                 case info_flags::algebraic:
238                         return !exponent.info(info_flags::integer) ||
239                                basis.info(inf);
240                 case info_flags::expanded:
241                         return (flags & status_flags::expanded);
242                 case info_flags::positive:
243                         return basis.info(info_flags::positive) && exponent.info(info_flags::real);
244                 case info_flags::nonnegative:
245                         return (basis.info(info_flags::positive) && exponent.info(info_flags::real)) ||
246                                (basis.info(info_flags::real) && exponent.info(info_flags::integer) && exponent.info(info_flags::even));
247                 case info_flags::has_indices: {
248                         if (flags & status_flags::has_indices)
249                                 return true;
250                         else if (flags & status_flags::has_no_indices)
251                                 return false;
252                         else if (basis.info(info_flags::has_indices)) {
253                                 setflag(status_flags::has_indices);
254                                 clearflag(status_flags::has_no_indices);
255                                 return true;
256                         } else {
257                                 clearflag(status_flags::has_indices);
258                                 setflag(status_flags::has_no_indices);
259                                 return false;
260                         }
261                 }
262         }
263         return inherited::info(inf);
264 }
265
266 size_t power::nops() const
267 {
268         return 2;
269 }
270
271 ex power::op(size_t i) const
272 {
273         GINAC_ASSERT(i<2);
274
275         return i==0 ? basis : exponent;
276 }
277
278 ex power::map(map_function & f) const
279 {
280         const ex &mapped_basis = f(basis);
281         const ex &mapped_exponent = f(exponent);
282
283         if (!are_ex_trivially_equal(basis, mapped_basis)
284          || !are_ex_trivially_equal(exponent, mapped_exponent))
285                 return (new power(mapped_basis, mapped_exponent))->setflag(status_flags::dynallocated);
286         else
287                 return *this;
288 }
289
290 bool power::is_polynomial(const ex & var) const
291 {
292         if (basis.is_polynomial(var)) {
293                 if (basis.has(var))
294                         // basis is non-constant polynomial in var
295                         return exponent.info(info_flags::nonnegint);
296                 else
297                         // basis is constant in var
298                         return !exponent.has(var);
299         }
300         // basis is a non-polynomial function of var
301         return false;
302 }
303
304 int power::degree(const ex & s) const
305 {
306         if (is_equal(ex_to<basic>(s)))
307                 return 1;
308         else if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
309                 if (basis.is_equal(s))
310                         return ex_to<numeric>(exponent).to_int();
311                 else
312                         return basis.degree(s) * ex_to<numeric>(exponent).to_int();
313         } else if (basis.has(s))
314                 throw(std::runtime_error("power::degree(): undefined degree because of non-integer exponent"));
315         else
316                 return 0;
317 }
318
319 int power::ldegree(const ex & s) const 
320 {
321         if (is_equal(ex_to<basic>(s)))
322                 return 1;
323         else if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
324                 if (basis.is_equal(s))
325                         return ex_to<numeric>(exponent).to_int();
326                 else
327                         return basis.ldegree(s) * ex_to<numeric>(exponent).to_int();
328         } else if (basis.has(s))
329                 throw(std::runtime_error("power::ldegree(): undefined degree because of non-integer exponent"));
330         else
331                 return 0;
332 }
333
334 ex power::coeff(const ex & s, int n) const
335 {
336         if (is_equal(ex_to<basic>(s)))
337                 return n==1 ? _ex1 : _ex0;
338         else if (!basis.is_equal(s)) {
339                 // basis not equal to s
340                 if (n == 0)
341                         return *this;
342                 else
343                         return _ex0;
344         } else {
345                 // basis equal to s
346                 if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
347                         // integer exponent
348                         int int_exp = ex_to<numeric>(exponent).to_int();
349                         if (n == int_exp)
350                                 return _ex1;
351                         else
352                                 return _ex0;
353                 } else {
354                         // non-integer exponents are treated as zero
355                         if (n == 0)
356                                 return *this;
357                         else
358                                 return _ex0;
359                 }
360         }
361 }
362
363 /** Perform automatic term rewriting rules in this class.  In the following
364  *  x, x1, x2,... stand for a symbolic variables of type ex and c, c1, c2...
365  *  stand for such expressions that contain a plain number.
366  *  - ^(x,0) -> 1  (also handles ^(0,0))
367  *  - ^(x,1) -> x
368  *  - ^(0,c) -> 0 or exception  (depending on the real part of c)
369  *  - ^(1,x) -> 1
370  *  - ^(c1,c2) -> *(c1^n,c1^(c2-n))  (so that 0<(c2-n)<1, try to evaluate roots, possibly in numerator and denominator of c1)
371  *  - ^(^(x,c1),c2) -> ^(x,c1*c2)  if x is positive and c1 is real.
372  *  - ^(^(x,c1),c2) -> ^(x,c1*c2)  (c2 integer or -1 < c1 <= 1 or (c1=-1 and c2>0), case c1=1 should not happen, see below!)
373  *  - ^(*(x,y,z),c) -> *(x^c,y^c,z^c)  (if c integer)
374  *  - ^(*(x,c1),c2) -> ^(x,c2)*c1^c2  (c1>0)
375  *  - ^(*(x,c1),c2) -> ^(-x,c2)*c1^c2  (c1<0)
376  *
377  *  @param level cut-off in recursive evaluation */
378 ex power::eval(int level) const
379 {
380         if ((level==1) && (flags & status_flags::evaluated))
381                 return *this;
382         else if (level == -max_recursion_level)
383                 throw(std::runtime_error("max recursion level reached"));
384         
385         const ex & ebasis    = level==1 ? basis    : basis.eval(level-1);
386         const ex & eexponent = level==1 ? exponent : exponent.eval(level-1);
387         
388         const numeric *num_basis = NULL;
389         const numeric *num_exponent = NULL;
390         
391         if (is_exactly_a<numeric>(ebasis)) {
392                 num_basis = &ex_to<numeric>(ebasis);
393         }
394         if (is_exactly_a<numeric>(eexponent)) {
395                 num_exponent = &ex_to<numeric>(eexponent);
396         }
397         
398         // ^(x,0) -> 1  (0^0 also handled here)
399         if (eexponent.is_zero()) {
400                 if (ebasis.is_zero())
401                         throw (std::domain_error("power::eval(): pow(0,0) is undefined"));
402                 else
403                         return _ex1;
404         }
405         
406         // ^(x,1) -> x
407         if (eexponent.is_equal(_ex1))
408                 return ebasis;
409
410         // ^(0,c1) -> 0 or exception  (depending on real value of c1)
411         if ( ebasis.is_zero() && num_exponent ) {
412                 if ((num_exponent->real()).is_zero())
413                         throw (std::domain_error("power::eval(): pow(0,I) is undefined"));
414                 else if ((num_exponent->real()).is_negative())
415                         throw (pole_error("power::eval(): division by zero",1));
416                 else
417                         return _ex0;
418         }
419
420         // ^(1,x) -> 1
421         if (ebasis.is_equal(_ex1))
422                 return _ex1;
423
424         // power of a function calculated by separate rules defined for this function
425         if (is_exactly_a<function>(ebasis))
426                 return ex_to<function>(ebasis).power(eexponent);
427
428         // Turn (x^c)^d into x^(c*d) in the case that x is positive and c is real.
429         if (is_exactly_a<power>(ebasis) && ebasis.op(0).info(info_flags::positive) && ebasis.op(1).info(info_flags::real))
430                 return power(ebasis.op(0), ebasis.op(1) * eexponent);
431
432         if ( num_exponent ) {
433
434                 // ^(c1,c2) -> c1^c2  (c1, c2 numeric(),
435                 // except if c1,c2 are rational, but c1^c2 is not)
436                 if ( num_basis ) {
437                         const bool basis_is_crational = num_basis->is_crational();
438                         const bool exponent_is_crational = num_exponent->is_crational();
439                         if (!basis_is_crational || !exponent_is_crational) {
440                                 // return a plain float
441                                 return (new numeric(num_basis->power(*num_exponent)))->setflag(status_flags::dynallocated |
442                                                                                                status_flags::evaluated |
443                                                                                                status_flags::expanded);
444                         }
445
446                         const numeric res = num_basis->power(*num_exponent);
447                         if (res.is_crational()) {
448                                 return res;
449                         }
450                         GINAC_ASSERT(!num_exponent->is_integer());  // has been handled by now
451
452                         // ^(c1,n/m) -> *(c1^q,c1^(n/m-q)), 0<(n/m-q)<1, q integer
453                         if (basis_is_crational && exponent_is_crational
454                             && num_exponent->is_real()
455                             && !num_exponent->is_integer()) {
456                                 const numeric n = num_exponent->numer();
457                                 const numeric m = num_exponent->denom();
458                                 numeric r;
459                                 numeric q = iquo(n, m, r);
460                                 if (r.is_negative()) {
461                                         r += m;
462                                         --q;
463                                 }
464                                 if (q.is_zero()) {  // the exponent was in the allowed range 0<(n/m)<1
465                                         if (num_basis->is_rational() && !num_basis->is_integer()) {
466                                                 // try it for numerator and denominator separately, in order to
467                                                 // partially simplify things like (5/8)^(1/3) -> 1/2*5^(1/3)
468                                                 const numeric bnum = num_basis->numer();
469                                                 const numeric bden = num_basis->denom();
470                                                 const numeric res_bnum = bnum.power(*num_exponent);
471                                                 const numeric res_bden = bden.power(*num_exponent);
472                                                 if (res_bnum.is_integer())
473                                                         return (new mul(power(bden,-*num_exponent),res_bnum))->setflag(status_flags::dynallocated | status_flags::evaluated);
474                                                 if (res_bden.is_integer())
475                                                         return (new mul(power(bnum,*num_exponent),res_bden.inverse()))->setflag(status_flags::dynallocated | status_flags::evaluated);
476                                         }
477                                         return this->hold();
478                                 } else {
479                                         // assemble resulting product, but allowing for a re-evaluation,
480                                         // because otherwise we'll end up with something like
481                                         //    (7/8)^(4/3)  ->  7/8*(1/2*7^(1/3))
482                                         // instead of 7/16*7^(1/3).
483                                         ex prod = power(*num_basis,r.div(m));
484                                         return prod*power(*num_basis,q);
485                                 }
486                         }
487                 }
488         
489                 // ^(^(x,c1),c2) -> ^(x,c1*c2)
490                 // (c1, c2 numeric(), c2 integer or -1 < c1 <= 1 or (c1=-1 and c2>0),
491                 // case c1==1 should not happen, see below!)
492                 if (is_exactly_a<power>(ebasis)) {
493                         const power & sub_power = ex_to<power>(ebasis);
494                         const ex & sub_basis = sub_power.basis;
495                         const ex & sub_exponent = sub_power.exponent;
496                         if (is_exactly_a<numeric>(sub_exponent)) {
497                                 const numeric & num_sub_exponent = ex_to<numeric>(sub_exponent);
498                                 GINAC_ASSERT(num_sub_exponent!=numeric(1));
499                                 if (num_exponent->is_integer() || (abs(num_sub_exponent) - (*_num1_p)).is_negative() ||
500                                     (num_sub_exponent == *_num_1_p && num_exponent->is_positive())) {
501                                         return power(sub_basis,num_sub_exponent.mul(*num_exponent));
502                                 }
503                         }
504                 }
505         
506                 // ^(*(x,y,z),c1) -> *(x^c1,y^c1,z^c1) (c1 integer)
507                 if (num_exponent->is_integer() && is_exactly_a<mul>(ebasis)) {
508                         return expand_mul(ex_to<mul>(ebasis), *num_exponent, 0);
509                 }
510
511                 // (2*x + 6*y)^(-4) -> 1/16*(x + 3*y)^(-4)
512                 if (num_exponent->is_integer() && is_exactly_a<add>(ebasis)) {
513                         numeric icont = ebasis.integer_content();
514                         const numeric lead_coeff = 
515                                 ex_to<numeric>(ex_to<add>(ebasis).seq.begin()->coeff).div(icont);
516
517                         const bool canonicalizable = lead_coeff.is_integer();
518                         const bool unit_normal = lead_coeff.is_pos_integer();
519                         if (canonicalizable && (! unit_normal))
520                                 icont = icont.mul(*_num_1_p);
521                         
522                         if (canonicalizable && (icont != *_num1_p)) {
523                                 const add& addref = ex_to<add>(ebasis);
524                                 add* addp = new add(addref);
525                                 addp->setflag(status_flags::dynallocated);
526                                 addp->clearflag(status_flags::hash_calculated);
527                                 addp->overall_coeff = ex_to<numeric>(addp->overall_coeff).div_dyn(icont);
528                                 for (epvector::iterator i = addp->seq.begin(); i != addp->seq.end(); ++i)
529                                         i->coeff = ex_to<numeric>(i->coeff).div_dyn(icont);
530
531                                 const numeric c = icont.power(*num_exponent);
532                                 if (likely(c != *_num1_p))
533                                         return (new mul(power(*addp, *num_exponent), c))->setflag(status_flags::dynallocated);
534                                 else
535                                         return power(*addp, *num_exponent);
536                         }
537                 }
538
539                 // ^(*(...,x;c1),c2) -> *(^(*(...,x;1),c2),c1^c2)  (c1, c2 numeric(), c1>0)
540                 // ^(*(...,x;c1),c2) -> *(^(*(...,x;-1),c2),(-c1)^c2)  (c1, c2 numeric(), c1<0)
541                 if (is_exactly_a<mul>(ebasis)) {
542                         GINAC_ASSERT(!num_exponent->is_integer()); // should have been handled above
543                         const mul & mulref = ex_to<mul>(ebasis);
544                         if (!mulref.overall_coeff.is_equal(_ex1)) {
545                                 const numeric & num_coeff = ex_to<numeric>(mulref.overall_coeff);
546                                 if (num_coeff.is_real()) {
547                                         if (num_coeff.is_positive()) {
548                                                 mul *mulp = new mul(mulref);
549                                                 mulp->overall_coeff = _ex1;
550                                                 mulp->setflag(status_flags::dynallocated);
551                                                 mulp->clearflag(status_flags::evaluated);
552                                                 mulp->clearflag(status_flags::hash_calculated);
553                                                 return (new mul(power(*mulp,exponent),
554                                                                 power(num_coeff,*num_exponent)))->setflag(status_flags::dynallocated);
555                                         } else {
556                                                 GINAC_ASSERT(num_coeff.compare(*_num0_p)<0);
557                                                 if (!num_coeff.is_equal(*_num_1_p)) {
558                                                         mul *mulp = new mul(mulref);
559                                                         mulp->overall_coeff = _ex_1;
560                                                         mulp->setflag(status_flags::dynallocated);
561                                                         mulp->clearflag(status_flags::evaluated);
562                                                         mulp->clearflag(status_flags::hash_calculated);
563                                                         return (new mul(power(*mulp,exponent),
564                                                                         power(abs(num_coeff),*num_exponent)))->setflag(status_flags::dynallocated);
565                                                 }
566                                         }
567                                 }
568                         }
569                 }
570
571                 // ^(nc,c1) -> ncmul(nc,nc,...) (c1 positive integer, unless nc is a matrix)
572                 if (num_exponent->is_pos_integer() &&
573                     ebasis.return_type() != return_types::commutative &&
574                     !is_a<matrix>(ebasis)) {
575                         return ncmul(exvector(num_exponent->to_int(), ebasis), true);
576                 }
577         }
578         
579         if (are_ex_trivially_equal(ebasis,basis) &&
580             are_ex_trivially_equal(eexponent,exponent)) {
581                 return this->hold();
582         }
583         return (new power(ebasis, eexponent))->setflag(status_flags::dynallocated |
584                                                        status_flags::evaluated);
585 }
586
587 ex power::evalf(int level) const
588 {
589         ex ebasis;
590         ex eexponent;
591         
592         if (level==1) {
593                 ebasis = basis;
594                 eexponent = exponent;
595         } else if (level == -max_recursion_level) {
596                 throw(std::runtime_error("max recursion level reached"));
597         } else {
598                 ebasis = basis.evalf(level-1);
599                 if (!is_exactly_a<numeric>(exponent))
600                         eexponent = exponent.evalf(level-1);
601                 else
602                         eexponent = exponent;
603         }
604
605         return power(ebasis,eexponent);
606 }
607
608 ex power::evalm() const
609 {
610         const ex ebasis = basis.evalm();
611         const ex eexponent = exponent.evalm();
612         if (is_a<matrix>(ebasis)) {
613                 if (is_exactly_a<numeric>(eexponent)) {
614                         return (new matrix(ex_to<matrix>(ebasis).pow(eexponent)))->setflag(status_flags::dynallocated);
615                 }
616         }
617         return (new power(ebasis, eexponent))->setflag(status_flags::dynallocated);
618 }
619
620 bool power::has(const ex & other, unsigned options) const
621 {
622         if (!(options & has_options::algebraic))
623                 return basic::has(other, options);
624         if (!is_a<power>(other))
625                 return basic::has(other, options);
626         if (!exponent.info(info_flags::integer) ||
627             !other.op(1).info(info_flags::integer))
628                 return basic::has(other, options);
629         if (exponent.info(info_flags::posint) &&
630             other.op(1).info(info_flags::posint) &&
631             ex_to<numeric>(exponent) > ex_to<numeric>(other.op(1)) &&
632             basis.match(other.op(0)))
633                 return true;
634         if (exponent.info(info_flags::negint) &&
635             other.op(1).info(info_flags::negint) &&
636             ex_to<numeric>(exponent) < ex_to<numeric>(other.op(1)) &&
637             basis.match(other.op(0)))
638                 return true;
639         return basic::has(other, options);
640 }
641
642 // from mul.cpp
643 extern bool tryfactsubs(const ex &, const ex &, int &, exmap&);
644
645 ex power::subs(const exmap & m, unsigned options) const
646 {       
647         const ex &subsed_basis = basis.subs(m, options);
648         const ex &subsed_exponent = exponent.subs(m, options);
649
650         if (!are_ex_trivially_equal(basis, subsed_basis)
651          || !are_ex_trivially_equal(exponent, subsed_exponent)) 
652                 return power(subsed_basis, subsed_exponent).subs_one_level(m, options);
653
654         if (!(options & subs_options::algebraic))
655                 return subs_one_level(m, options);
656
657         for (exmap::const_iterator it = m.begin(); it != m.end(); ++it) {
658                 int nummatches = std::numeric_limits<int>::max();
659                 exmap repls;
660                 if (tryfactsubs(*this, it->first, nummatches, repls)) {
661                         ex anum = it->second.subs(repls, subs_options::no_pattern);
662                         ex aden = it->first.subs(repls, subs_options::no_pattern);
663                         ex result = (*this)*power(anum/aden, nummatches);
664                         return (ex_to<basic>(result)).subs_one_level(m, options);
665                 }
666         }
667
668         return subs_one_level(m, options);
669 }
670
671 ex power::eval_ncmul(const exvector & v) const
672 {
673         return inherited::eval_ncmul(v);
674 }
675
676 ex power::conjugate() const
677 {
678         // conjugate(pow(x,y))==pow(conjugate(x),conjugate(y)) unless on the
679         // branch cut which runs along the negative real axis.
680         if (basis.info(info_flags::positive)) {
681                 ex newexponent = exponent.conjugate();
682                 if (are_ex_trivially_equal(exponent, newexponent)) {
683                         return *this;
684                 }
685                 return (new power(basis, newexponent))->setflag(status_flags::dynallocated);
686         }
687         if (exponent.info(info_flags::integer)) {
688                 ex newbasis = basis.conjugate();
689                 if (are_ex_trivially_equal(basis, newbasis)) {
690                         return *this;
691                 }
692                 return (new power(newbasis, exponent))->setflag(status_flags::dynallocated);
693         }
694         return conjugate_function(*this).hold();
695 }
696
697 ex power::real_part() const
698 {
699         // basis == a+I*b, exponent == c+I*d
700         const ex a = basis.real_part();
701         const ex c = exponent.real_part();
702         if (basis.is_equal(a) && exponent.is_equal(c)) {
703                 // Re(a^c)
704                 return *this;
705         }
706
707         const ex b = basis.imag_part();
708         if (exponent.info(info_flags::integer)) {
709                 // Re((a+I*b)^c)  w/  c âˆˆ â„¤
710                 long N = ex_to<numeric>(c).to_long();
711                 // Use real terms in Binomial expansion to construct
712                 // Re(expand(power(a+I*b, N))).
713                 long NN = N > 0 ? N : -N;
714                 ex numer = N > 0 ? _ex1 : power(power(a,2) + power(b,2), NN);
715                 ex result = 0;
716                 for (long n = 0; n <= NN; n += 2) {
717                         ex term = binomial(NN, n) * power(a, NN-n) * power(b, n) / numer;
718                         if (n % 4 == 0) {
719                                 result += term;  // sign: I^n w/ n == 4*m
720                         } else {
721                                 result -= term;  // sign: I^n w/ n == 4*m+2
722                         }
723                 }
724                 return result;
725         }
726
727         // Re((a+I*b)^(c+I*d))
728         const ex d = exponent.imag_part();
729         return power(abs(basis),c)*exp(-d*atan2(b,a))*cos(c*atan2(b,a)+d*log(abs(basis)));
730 }
731
732 ex power::imag_part() const
733 {
734         const ex a = basis.real_part();
735         const ex c = exponent.real_part();
736         if (basis.is_equal(a) && exponent.is_equal(c)) {
737                 // Im(a^c)
738                 return 0;
739         }
740
741         const ex b = basis.imag_part();
742         if (exponent.info(info_flags::integer)) {
743                 // Im((a+I*b)^c)  w/  c âˆˆ â„¤
744                 long N = ex_to<numeric>(c).to_long();
745                 // Use imaginary terms in Binomial expansion to construct
746                 // Im(expand(power(a+I*b, N))).
747                 long p = N > 0 ? 1 : 3;  // modulus for positive sign
748                 long NN = N > 0 ? N : -N;
749                 ex numer = N > 0 ? _ex1 : power(power(a,2) + power(b,2), NN);
750                 ex result = 0;
751                 for (long n = 1; n <= NN; n += 2) {
752                         ex term = binomial(NN, n) * power(a, NN-n) * power(b, n) / numer;
753                         if (n % 4 == p) {
754                                 result += term;  // sign: I^n w/ n == 4*m+p
755                         } else {
756                                 result -= term;  // sign: I^n w/ n == 4*m+2+p
757                         }
758                 }
759                 return result;
760         }
761
762         // Im((a+I*b)^(c+I*d))
763         const ex d = exponent.imag_part();
764         return power(abs(basis),c)*exp(-d*atan2(b,a))*sin(c*atan2(b,a)+d*log(abs(basis)));
765 }
766
767 // protected
768
769 /** Implementation of ex::diff() for a power.
770  *  @see ex::diff */
771 ex power::derivative(const symbol & s) const
772 {
773         if (is_a<numeric>(exponent)) {
774                 // D(b^r) = r * b^(r-1) * D(b) (faster than the formula below)
775                 epvector newseq;
776                 newseq.reserve(2);
777                 newseq.push_back(expair(basis, exponent - _ex1));
778                 newseq.push_back(expair(basis.diff(s), _ex1));
779                 return mul(newseq, exponent);
780         } else {
781                 // D(b^e) = b^e * (D(e)*ln(b) + e*D(b)/b)
782                 return mul(*this,
783                            add(mul(exponent.diff(s), log(basis)),
784                            mul(mul(exponent, basis.diff(s)), power(basis, _ex_1))));
785         }
786 }
787
788 int power::compare_same_type(const basic & other) const
789 {
790         GINAC_ASSERT(is_exactly_a<power>(other));
791         const power &o = static_cast<const power &>(other);
792
793         int cmpval = basis.compare(o.basis);
794         if (cmpval)
795                 return cmpval;
796         else
797                 return exponent.compare(o.exponent);
798 }
799
800 unsigned power::return_type() const
801 {
802         return basis.return_type();
803 }
804
805 return_type_t power::return_type_tinfo() const
806 {
807         return basis.return_type_tinfo();
808 }
809
810 ex power::expand(unsigned options) const
811 {
812         if (is_a<symbol>(basis) && exponent.info(info_flags::integer)) {
813                 // A special case worth optimizing.
814                 setflag(status_flags::expanded);
815                 return *this;
816         }
817
818         // (x*p)^c -> x^c * p^c, if p>0
819         // makes sense before expanding the basis
820         if (is_exactly_a<mul>(basis) && !basis.info(info_flags::indefinite)) {
821                 const mul &m = ex_to<mul>(basis);
822                 exvector prodseq;
823                 epvector powseq;
824                 prodseq.reserve(m.seq.size() + 1);
825                 powseq.reserve(m.seq.size() + 1);
826                 epvector::const_iterator last = m.seq.end();
827                 epvector::const_iterator cit = m.seq.begin();
828                 bool possign = true;
829
830                 // search for positive/negative factors
831                 while (cit!=last) {
832                         ex e=m.recombine_pair_to_ex(*cit);
833                         if (e.info(info_flags::positive))
834                                 prodseq.push_back(pow(e, exponent).expand(options));
835                         else if (e.info(info_flags::negative)) {
836                                 prodseq.push_back(pow(-e, exponent).expand(options));
837                                 possign = !possign;
838                         } else
839                                 powseq.push_back(*cit);
840                         ++cit;
841                 }
842
843                 // take care on the numeric coefficient
844                 ex coeff=(possign? _ex1 : _ex_1);
845                 if (m.overall_coeff.info(info_flags::positive) && m.overall_coeff != _ex1)
846                         prodseq.push_back(power(m.overall_coeff, exponent));
847                 else if (m.overall_coeff.info(info_flags::negative) && m.overall_coeff != _ex_1)
848                         prodseq.push_back(power(-m.overall_coeff, exponent));
849                 else
850                         coeff *= m.overall_coeff;
851
852                 // If positive/negative factors are found, then extract them.
853                 // In either case we set a flag to avoid the second run on a part
854                 // which does not have positive/negative terms.
855                 if (prodseq.size() > 0) {
856                         ex newbasis = coeff*mul(powseq);
857                         ex_to<basic>(newbasis).setflag(status_flags::purely_indefinite);
858                         return ((new mul(prodseq))->setflag(status_flags::dynallocated)*(new power(newbasis, exponent))->setflag(status_flags::dynallocated).expand(options)).expand(options);
859                 } else
860                         ex_to<basic>(basis).setflag(status_flags::purely_indefinite);
861         }
862
863         const ex expanded_basis = basis.expand(options);
864         const ex expanded_exponent = exponent.expand(options);
865         
866         // x^(a+b) -> x^a * x^b
867         if (is_exactly_a<add>(expanded_exponent)) {
868                 const add &a = ex_to<add>(expanded_exponent);
869                 exvector distrseq;
870                 distrseq.reserve(a.seq.size() + 1);
871                 epvector::const_iterator last = a.seq.end();
872                 epvector::const_iterator cit = a.seq.begin();
873                 while (cit!=last) {
874                         distrseq.push_back(power(expanded_basis, a.recombine_pair_to_ex(*cit)));
875                         ++cit;
876                 }
877                 
878                 // Make sure that e.g. (x+y)^(2+a) expands the (x+y)^2 factor
879                 if (ex_to<numeric>(a.overall_coeff).is_integer()) {
880                         const numeric &num_exponent = ex_to<numeric>(a.overall_coeff);
881                         int int_exponent = num_exponent.to_int();
882                         if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
883                                 distrseq.push_back(expand_add(ex_to<add>(expanded_basis), int_exponent, options));
884                         else
885                                 distrseq.push_back(power(expanded_basis, a.overall_coeff));
886                 } else
887                         distrseq.push_back(power(expanded_basis, a.overall_coeff));
888                 
889                 // Make sure that e.g. (x+y)^(1+a) -> x*(x+y)^a + y*(x+y)^a
890                 ex r = (new mul(distrseq))->setflag(status_flags::dynallocated);
891                 return r.expand(options);
892         }
893         
894         if (!is_exactly_a<numeric>(expanded_exponent) ||
895                 !ex_to<numeric>(expanded_exponent).is_integer()) {
896                 if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent)) {
897                         return this->hold();
898                 } else {
899                         return (new power(expanded_basis,expanded_exponent))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
900                 }
901         }
902         
903         // integer numeric exponent
904         const numeric & num_exponent = ex_to<numeric>(expanded_exponent);
905         int int_exponent = num_exponent.to_int();
906         
907         // (x+y)^n, n>0
908         if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
909                 return expand_add(ex_to<add>(expanded_basis), int_exponent, options);
910         
911         // (x*y)^n -> x^n * y^n
912         if (is_exactly_a<mul>(expanded_basis))
913                 return expand_mul(ex_to<mul>(expanded_basis), num_exponent, options, true);
914         
915         // cannot expand further
916         if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent))
917                 return this->hold();
918         else
919                 return (new power(expanded_basis,expanded_exponent))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
920 }
921
922 //////////
923 // new virtual functions which can be overridden by derived classes
924 //////////
925
926 // none
927
928 //////////
929 // non-virtual functions in this class
930 //////////
931
932 namespace {  // anonymous namespace for power::expand_add() helpers
933
934 /** Helper class to generate all bounded combinatorial partitions of an integer
935  *  n with exactly m parts (including zero parts) in non-decreasing order.
936  */
937 class partition_generator {
938 private:
939         // Partitions n into m parts, not including zero parts.
940         // (Cf. OEIS sequence A008284; implementation adapted from Jörg Arndt's
941         // FXT library)
942         struct mpartition2
943         {
944                 // partition: x[1] + x[2] + ... + x[m] = n and sentinel x[0] == 0
945                 std::vector<int> x;
946                 int n;   // n>0
947                 int m;   // 0<m<=n
948                 mpartition2(unsigned n_, unsigned m_)
949                   : x(m_+1), n(n_), m(m_)
950                 {
951                         for (int k=1; k<m; ++k)
952                                 x[k] = 1;
953                         x[m] = n - m + 1;
954                 }
955                 bool next_partition()
956                 {
957                         int u = x[m];  // last element
958                         int k = m;
959                         int s = u;
960                         while (--k) {
961                                 s += x[k];
962                                 if (x[k] + 2 <= u)
963                                         break;
964                         }
965                         if (k==0)
966                                 return false;  // current is last
967                         int f = x[k] + 1;
968                         while (k < m) {
969                                 x[k] = f;
970                                 s -= f;
971                                 ++k;
972                         }
973                         x[m] = s;
974                         return true;
975                 }
976         } mpgen;
977         int m;  // number of parts 0<m<=n
978         mutable std::vector<int> partition;  // current partition
979 public:
980         partition_generator(unsigned n_, unsigned m_)
981           : mpgen(n_, 1), m(m_), partition(m_)
982         { }
983         // returns current partition in non-decreasing order, padded with zeros
984         const std::vector<int>& current() const
985         {
986                 for (int i = 0; i < m - mpgen.m; ++i)
987                         partition[i] = 0;  // pad with zeros
988
989                 for (int i = m - mpgen.m; i < m; ++i)
990                         partition[i] = mpgen.x[i - m + mpgen.m + 1];
991
992                 return partition;
993         }
994         bool next()
995         {
996                 if (!mpgen.next_partition()) {
997                         if (mpgen.m == m || mpgen.m == mpgen.n)
998                                 return false;  // current is last
999                         // increment number of parts
1000                         mpgen = mpartition2(mpgen.n, mpgen.m + 1);
1001                 }
1002                 return true;
1003         }
1004 };
1005
1006 /** Helper class to generate all compositions of a partition of an integer n,
1007  *  starting with the compositions which has non-decreasing order.
1008  */
1009 class composition_generator {
1010 private:
1011         // Generates all distinct permutations of a multiset.
1012         // (Based on Aaron Williams' algorithm 1 from "Loopless Generation of
1013         // Multiset Permutations using a Constant Number of Variables by Prefix
1014         // Shifts." <http://webhome.csc.uvic.ca/~haron/CoolMulti.pdf>)
1015         struct coolmulti {
1016                 // element of singly linked list
1017                 struct element {
1018                         int value;
1019                         element* next;
1020                         element(int val, element* n)
1021                           : value(val), next(n) {}
1022                         ~element()
1023                         {   // recurses down to the end of the singly linked list
1024                                 delete next;
1025                         }
1026                 };
1027                 element *head, *i, *after_i;
1028                 // NB: Partition must be sorted in non-decreasing order.
1029                 explicit coolmulti(const std::vector<int>& partition)
1030                 {
1031                         head = NULL;
1032                         for (unsigned n = 0; n < partition.size(); ++n) {
1033                                 head = new element(partition[n], head);
1034                                 if (n <= 1)
1035                                         i = head;
1036                         }
1037                         after_i = i->next;
1038                 }
1039                 ~coolmulti()
1040                 {   // deletes singly linked list
1041                         delete head;
1042                 }
1043                 void next_permutation()
1044                 {
1045                         element *before_k;
1046                         if (after_i->next != NULL && i->value >= after_i->next->value)
1047                                 before_k = after_i;
1048                         else
1049                                 before_k = i;
1050                         element *k = before_k->next;
1051                         before_k->next = k->next;
1052                         k->next = head;
1053                         if (k->value < head->value)
1054                                 i = k;
1055                         after_i = i->next;
1056                         head = k;
1057                 }
1058                 bool finished() const
1059                 {
1060                         return after_i->next == NULL && after_i->value >= head->value;
1061                 }
1062         } cmgen;
1063         bool atend;  // needed for simplifying iteration over permutations
1064         bool trivial;  // likewise, true if all elements are equal
1065         mutable std::vector<int> composition;  // current compositions
1066 public:
1067         explicit composition_generator(const std::vector<int>& partition)
1068           : cmgen(partition), atend(false), trivial(true), composition(partition.size())
1069         {
1070                 for (unsigned i=1; i<partition.size(); ++i)
1071                         trivial = trivial && (partition[0] == partition[i]);
1072         }
1073         const std::vector<int>& current() const
1074         {
1075                 coolmulti::element* it = cmgen.head;
1076                 size_t i = 0;
1077                 while (it != NULL) {
1078                         composition[i] = it->value;
1079                         it = it->next;
1080                         ++i;
1081                 }
1082                 return composition;
1083         }
1084         bool next()
1085         {
1086                 // This ugly contortion is needed because the original coolmulti
1087                 // algorithm requires code duplication of the payload procedure,
1088                 // one before the loop and one inside it.
1089                 if (trivial || atend)
1090                         return false;
1091                 cmgen.next_permutation();
1092                 atend = cmgen.finished();
1093                 return true;
1094         }
1095 };
1096
1097 /** Helper function to compute the multinomial coefficient n!/(p1!*p2!*...*pk!)
1098  *  where n = p1+p2+...+pk, i.e. p is a partition of n.
1099  */
1100 const numeric
1101 multinomial_coefficient(const std::vector<int> & p)
1102 {
1103         numeric n = 0, d = 1;
1104         std::vector<int>::const_iterator it = p.begin(), itend = p.end();
1105         while (it != itend) {
1106                 n += numeric(*it);
1107                 d *= factorial(numeric(*it));
1108                 ++it;
1109         }
1110         return factorial(numeric(n)) / d;
1111 }
1112
1113 }  // anonymous namespace
1114
1115 /** expand a^n where a is an add and n is a positive integer.
1116  *  @see power::expand */
1117 ex power::expand_add(const add & a, int n, unsigned options) const
1118 {
1119         // The special case power(+(x,...y;x),2) can be optimized better.
1120         if (n==2)
1121                 return expand_add_2(a, options);
1122
1123         // method:
1124         //
1125         // Consider base as the sum of all symbolic terms and the overall numeric
1126         // coefficient and apply the binomial theorem:
1127         // S = power(+(x,...,z;c),n)
1128         //   = power(+(+(x,...,z;0);c),n)
1129         //   = sum(binomial(n,k)*power(+(x,...,z;0),k)*c^(n-k), k=1..n) + c^n
1130         // Then, apply the multinomial theorem to expand all power(+(x,...,z;0),k):
1131         // The multinomial theorem is computed by an outer loop over all
1132         // partitions of the exponent and an inner loop over all compositions of
1133         // that partition. This method makes the expansion a combinatorial
1134         // problem and allows us to directly construct the expanded sum and also
1135         // to re-use the multinomial coefficients (since they depend only on the
1136         // partition, not on the composition).
1137         // 
1138         // multinomial power(+(x,y,z;0),3) example:
1139         // partition : compositions                : multinomial coefficient
1140         // [0,0,3]   : [3,0,0],[0,3,0],[0,0,3]     : 3!/(3!*0!*0!) = 1
1141         // [0,1,2]   : [2,1,0],[1,2,0],[2,0,1],... : 3!/(2!*1!*0!) = 3
1142         // [1,1,1]   : [1,1,1]                     : 3!/(1!*1!*1!) = 6
1143         //  =>  (x + y + z)^3 =
1144         //        x^3 + y^3 + z^3
1145         //      + 3*x^2*y + 3*x*y^2 + 3*y^2*z + 3*y*z^2 + 3*x*z^2 + 3*x^2*z
1146         //      + 6*x*y*z
1147         //
1148         // multinomial power(+(x,y,z;0),4) example:
1149         // partition : compositions                : multinomial coefficient
1150         // [0,0,4]   : [4,0,0],[0,4,0],[0,0,4]     : 4!/(4!*0!*0!) = 1
1151         // [0,1,3]   : [3,1,0],[1,3,0],[3,0,1],... : 4!/(3!*1!*0!) = 4
1152         // [0,2,2]   : [2,2,0],[2,0,2],[0,2,2]     : 4!/(2!*2!*0!) = 6
1153         // [1,1,2]   : [2,1,1],[1,2,1],[1,1,2]     : 4!/(2!*1!*1!) = 12
1154         // (no [1,1,1,1] partition since it has too many parts)
1155         //  =>  (x + y + z)^4 =
1156         //        x^4 + y^4 + z^4
1157         //      + 4*x^3*y + 4*x*y^3 + 4*y^3*z + 4*y*z^3 + 4*x*z^3 + 4*x^3*z
1158         //      + 6*x^2*y^2 + 6*y^2*z^2 + 6*x^2*z^2
1159         //      + 12*x^2*y*z + 12*x*y^2*z + 12*x*y*z^2
1160         //
1161         // Summary:
1162         // r = 0
1163         // for k from 0 to n:
1164         //     f = c^(n-k)*binomial(n,k)
1165         //     for p in all partitions of n with m parts (including zero parts):
1166         //         h = f * multinomial coefficient of p
1167         //         for c in all compositions of p:
1168         //             t = 1
1169         //             for e in all elements of c:
1170         //                 t = t * a[e]^e
1171         //             r = r + h*t
1172         // return r
1173
1174         epvector result;
1175         // The number of terms will be the number of combinatorial compositions,
1176         // i.e. the number of unordered arrangements of m nonnegative integers
1177         // which sum up to n.  It is frequently written as C_n(m) and directly
1178         // related with binomial coefficients: binomial(n+m-1,m-1).
1179         size_t result_size = binomial(numeric(n+a.nops()-1), numeric(a.nops()-1)).to_int();
1180         if (!a.overall_coeff.is_zero()) {
1181                 // the result's overall_coeff is one of the terms
1182                 --result_size;
1183         }
1184         result.reserve(result_size);
1185
1186         // Iterate over all terms in binomial expansion of
1187         // S = power(+(x,...,z;c),n)
1188         //   = sum(binomial(n,k)*power(+(x,...,z;0),k)*c^(n-k), k=1..n) + c^n
1189         for (int k = 1; k <= n; ++k) {
1190                 numeric binomial_coefficient;  // binomial(n,k)*c^(n-k)
1191                 if (a.overall_coeff.is_zero()) {
1192                         // degenerate case with zero overall_coeff:
1193                         // apply multinomial theorem directly to power(+(x,...z;0),n)
1194                         binomial_coefficient = 1;
1195                         if (k < n) {
1196                                 continue;
1197                         }
1198                 } else {
1199                         binomial_coefficient = binomial(numeric(n), numeric(k)) * pow(ex_to<numeric>(a.overall_coeff), numeric(n-k));
1200                 }
1201
1202                 // Multinomial expansion of power(+(x,...,z;0),k)*c^(n-k):
1203                 // Iterate over all partitions of k with exactly as many parts as
1204                 // there are symbolic terms in the basis (including zero parts).
1205                 partition_generator partitions(k, a.seq.size());
1206                 do {
1207                         const std::vector<int>& partition = partitions.current();
1208                         // All monomials of this partition have the same number of terms and the same coefficient.
1209                         const unsigned msize = count_if(partition.begin(), partition.end(), bind2nd(std::greater<int>(), 0));
1210                         const numeric coeff = multinomial_coefficient(partition) * binomial_coefficient;
1211
1212                         // Iterate over all compositions of the current partition.
1213                         composition_generator compositions(partition);
1214                         do {
1215                                 const std::vector<int>& exponent = compositions.current();
1216                                 exvector monomial;
1217                                 monomial.reserve(msize);
1218                                 numeric factor = coeff;
1219                                 for (unsigned i = 0; i < exponent.size(); ++i) {
1220                                         const ex & r = a.seq[i].rest;
1221                                         GINAC_ASSERT(!is_exactly_a<add>(r));
1222                                         GINAC_ASSERT(!is_exactly_a<power>(r) ||
1223                                                      !is_exactly_a<numeric>(ex_to<power>(r).exponent) ||
1224                                                      !ex_to<numeric>(ex_to<power>(r).exponent).is_pos_integer() ||
1225                                                      !is_exactly_a<add>(ex_to<power>(r).basis) ||
1226                                                      !is_exactly_a<mul>(ex_to<power>(r).basis) ||
1227                                                      !is_exactly_a<power>(ex_to<power>(r).basis));
1228                                         GINAC_ASSERT(is_exactly_a<numeric>(a.seq[i].coeff));
1229                                         const numeric & c = ex_to<numeric>(a.seq[i].coeff);
1230                                         if (exponent[i] == 0) {
1231                                                 // optimize away
1232                                         } else if (exponent[i] == 1) {
1233                                                 // optimized
1234                                                 monomial.push_back(r);
1235                                                 if (c != *_num1_p)
1236                                                         factor = factor.mul(c);
1237                                         } else { // general case exponent[i] > 1
1238                                                 monomial.push_back((new power(r, exponent[i]))->setflag(status_flags::dynallocated));
1239                                                 if (c != *_num1_p)
1240                                                         factor = factor.mul(c.power(exponent[i]));
1241                                         }
1242                                 }
1243                                 result.push_back(a.combine_ex_with_coeff_to_pair(mul(monomial).expand(options), factor));
1244                         } while (compositions.next());
1245                 } while (partitions.next());
1246         }
1247
1248         GINAC_ASSERT(result.size() == result_size);
1249
1250         if (a.overall_coeff.is_zero()) {
1251                 return (new add(result))->setflag(status_flags::dynallocated |
1252                                                   status_flags::expanded);
1253         } else {
1254                 return (new add(result, ex_to<numeric>(a.overall_coeff).power(n)))->setflag(status_flags::dynallocated |
1255                                                                                             status_flags::expanded);
1256         }
1257 }
1258
1259
1260 /** Special case of power::expand_add. Expands a^2 where a is an add.
1261  *  @see power::expand_add */
1262 ex power::expand_add_2(const add & a, unsigned options) const
1263 {
1264         epvector sum;
1265         size_t a_nops = a.nops();
1266         sum.reserve((a_nops*(a_nops+1))/2);
1267         epvector::const_iterator last = a.seq.end();
1268
1269         // power(+(x,...,z;c),2)=power(+(x,...,z;0),2)+2*c*+(x,...,z;0)+c*c
1270         // first part: ignore overall_coeff and expand other terms
1271         for (epvector::const_iterator cit0=a.seq.begin(); cit0!=last; ++cit0) {
1272                 const ex & r = cit0->rest;
1273                 const ex & c = cit0->coeff;
1274                 
1275                 GINAC_ASSERT(!is_exactly_a<add>(r));
1276                 GINAC_ASSERT(!is_exactly_a<power>(r) ||
1277                              !is_exactly_a<numeric>(ex_to<power>(r).exponent) ||
1278                              !ex_to<numeric>(ex_to<power>(r).exponent).is_pos_integer() ||
1279                              !is_exactly_a<add>(ex_to<power>(r).basis) ||
1280                              !is_exactly_a<mul>(ex_to<power>(r).basis) ||
1281                              !is_exactly_a<power>(ex_to<power>(r).basis));
1282                 
1283                 if (c.is_equal(_ex1)) {
1284                         if (is_exactly_a<mul>(r)) {
1285                                 sum.push_back(a.combine_ex_with_coeff_to_pair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
1286                                                                               _ex1));
1287                         } else {
1288                                 sum.push_back(a.combine_ex_with_coeff_to_pair((new power(r,_ex2))->setflag(status_flags::dynallocated),
1289                                                                               _ex1));
1290                         }
1291                 } else {
1292                         if (is_exactly_a<mul>(r)) {
1293                                 sum.push_back(a.combine_ex_with_coeff_to_pair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
1294                                                      ex_to<numeric>(c).power_dyn(*_num2_p)));
1295                         } else {
1296                                 sum.push_back(a.combine_ex_with_coeff_to_pair((new power(r,_ex2))->setflag(status_flags::dynallocated),
1297                                                      ex_to<numeric>(c).power_dyn(*_num2_p)));
1298                         }
1299                 }
1300
1301                 for (epvector::const_iterator cit1=cit0+1; cit1!=last; ++cit1) {
1302                         const ex & r1 = cit1->rest;
1303                         const ex & c1 = cit1->coeff;
1304                         sum.push_back(a.combine_ex_with_coeff_to_pair(mul(r,r1).expand(options),
1305                                                                       _num2_p->mul(ex_to<numeric>(c)).mul_dyn(ex_to<numeric>(c1))));
1306                 }
1307         }
1308         
1309         GINAC_ASSERT(sum.size()==(a.seq.size()*(a.seq.size()+1))/2);
1310         
1311         // second part: add terms coming from overall_coeff (if != 0)
1312         if (!a.overall_coeff.is_zero()) {
1313                 epvector::const_iterator i = a.seq.begin(), end = a.seq.end();
1314                 while (i != end) {
1315                         sum.push_back(a.combine_pair_with_coeff_to_pair(*i, ex_to<numeric>(a.overall_coeff).mul_dyn(*_num2_p)));
1316                         ++i;
1317                 }
1318                 sum.push_back(expair(ex_to<numeric>(a.overall_coeff).power_dyn(*_num2_p),_ex1));
1319         }
1320         
1321         GINAC_ASSERT(sum.size()==(a_nops*(a_nops+1))/2);
1322         
1323         return (new add(sum))->setflag(status_flags::dynallocated | status_flags::expanded);
1324 }
1325
1326 /** Expand factors of m in m^n where m is a mul and n is an integer.
1327  *  @see power::expand */
1328 ex power::expand_mul(const mul & m, const numeric & n, unsigned options, bool from_expand) const
1329 {
1330         GINAC_ASSERT(n.is_integer());
1331
1332         if (n.is_zero()) {
1333                 return _ex1;
1334         }
1335
1336         // do not bother to rename indices if there are no any.
1337         if (!(options & expand_options::expand_rename_idx) &&
1338             m.info(info_flags::has_indices))
1339                 options |= expand_options::expand_rename_idx;
1340         // Leave it to multiplication since dummy indices have to be renamed
1341         if ((options & expand_options::expand_rename_idx) &&
1342             (get_all_dummy_indices(m).size() > 0) && n.is_positive()) {
1343                 ex result = m;
1344                 exvector va = get_all_dummy_indices(m);
1345                 sort(va.begin(), va.end(), ex_is_less());
1346
1347                 for (int i=1; i < n.to_int(); i++)
1348                         result *= rename_dummy_indices_uniquely(va, m);
1349                 return result;
1350         }
1351
1352         epvector distrseq;
1353         distrseq.reserve(m.seq.size());
1354         bool need_reexpand = false;
1355
1356         epvector::const_iterator last = m.seq.end();
1357         epvector::const_iterator cit = m.seq.begin();
1358         while (cit!=last) {
1359                 expair p = m.combine_pair_with_coeff_to_pair(*cit, n);
1360                 if (from_expand && is_exactly_a<add>(cit->rest) && ex_to<numeric>(p.coeff).is_pos_integer()) {
1361                         // this happens when e.g. (a+b)^(1/2) gets squared and
1362                         // the resulting product needs to be reexpanded
1363                         need_reexpand = true;
1364                 }
1365                 distrseq.push_back(p);
1366                 ++cit;
1367         }
1368
1369         const mul & result = static_cast<const mul &>((new mul(distrseq, ex_to<numeric>(m.overall_coeff).power_dyn(n)))->setflag(status_flags::dynallocated));
1370         if (need_reexpand)
1371                 return ex(result).expand(options);
1372         if (from_expand)
1373                 return result.setflag(status_flags::expanded);
1374         return result;
1375 }
1376
1377 GINAC_BIND_UNARCHIVER(power);
1378
1379 } // namespace GiNaC