]> www.ginac.de Git - ginac.git/blob - ginac/power.cpp
added check for power::get_free_indices()
[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-2004 Johannes Gutenberg University Mainz, Germany
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 2 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, write to the Free Software
20  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 #include <vector>
24 #include <iostream>
25 #include <stdexcept>
26 #include <limits>
27
28 #include "power.h"
29 #include "expairseq.h"
30 #include "add.h"
31 #include "mul.h"
32 #include "ncmul.h"
33 #include "numeric.h"
34 #include "constant.h"
35 #include "operators.h"
36 #include "inifcns.h" // for log() in power::derivative()
37 #include "matrix.h"
38 #include "indexed.h"
39 #include "symbol.h"
40 #include "lst.h"
41 #include "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                 case info_flags::rational_function:
227                         return exponent.info(info_flags::integer);
228                 case info_flags::algebraic:
229                         return (!exponent.info(info_flags::integer) ||
230                                         basis.info(inf));
231         }
232         return inherited::info(inf);
233 }
234
235 size_t power::nops() const
236 {
237         return 2;
238 }
239
240 ex power::op(size_t i) const
241 {
242         GINAC_ASSERT(i<2);
243
244         return i==0 ? basis : exponent;
245 }
246
247 ex power::map(map_function & f) const
248 {
249         const ex &mapped_basis = f(basis);
250         const ex &mapped_exponent = f(exponent);
251
252         if (!are_ex_trivially_equal(basis, mapped_basis)
253          || !are_ex_trivially_equal(exponent, mapped_exponent))
254                 return (new power(mapped_basis, mapped_exponent))->setflag(status_flags::dynallocated);
255         else
256                 return *this;
257 }
258
259 int power::degree(const ex & s) const
260 {
261         if (is_equal(ex_to<basic>(s)))
262                 return 1;
263         else if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
264                 if (basis.is_equal(s))
265                         return ex_to<numeric>(exponent).to_int();
266                 else
267                         return basis.degree(s) * ex_to<numeric>(exponent).to_int();
268         } else if (basis.has(s))
269                 throw(std::runtime_error("power::degree(): undefined degree because of non-integer exponent"));
270         else
271                 return 0;
272 }
273
274 int power::ldegree(const ex & s) const 
275 {
276         if (is_equal(ex_to<basic>(s)))
277                 return 1;
278         else if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
279                 if (basis.is_equal(s))
280                         return ex_to<numeric>(exponent).to_int();
281                 else
282                         return basis.ldegree(s) * ex_to<numeric>(exponent).to_int();
283         } else if (basis.has(s))
284                 throw(std::runtime_error("power::ldegree(): undefined degree because of non-integer exponent"));
285         else
286                 return 0;
287 }
288
289 ex power::coeff(const ex & s, int n) const
290 {
291         if (is_equal(ex_to<basic>(s)))
292                 return n==1 ? _ex1 : _ex0;
293         else if (!basis.is_equal(s)) {
294                 // basis not equal to s
295                 if (n == 0)
296                         return *this;
297                 else
298                         return _ex0;
299         } else {
300                 // basis equal to s
301                 if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
302                         // integer exponent
303                         int int_exp = ex_to<numeric>(exponent).to_int();
304                         if (n == int_exp)
305                                 return _ex1;
306                         else
307                                 return _ex0;
308                 } else {
309                         // non-integer exponents are treated as zero
310                         if (n == 0)
311                                 return *this;
312                         else
313                                 return _ex0;
314                 }
315         }
316 }
317
318 /** Perform automatic term rewriting rules in this class.  In the following
319  *  x, x1, x2,... stand for a symbolic variables of type ex and c, c1, c2...
320  *  stand for such expressions that contain a plain number.
321  *  - ^(x,0) -> 1  (also handles ^(0,0))
322  *  - ^(x,1) -> x
323  *  - ^(0,c) -> 0 or exception  (depending on the real part of c)
324  *  - ^(1,x) -> 1
325  *  - ^(c1,c2) -> *(c1^n,c1^(c2-n))  (so that 0<(c2-n)<1, try to evaluate roots, possibly in numerator and denominator of c1)
326  *  - ^(^(x,c1),c2) -> ^(x,c1*c2)  (c2 integer or -1 < c1 <= 1, case c1=1 should not happen, see below!)
327  *  - ^(*(x,y,z),c) -> *(x^c,y^c,z^c)  (if c integer)
328  *  - ^(*(x,c1),c2) -> ^(x,c2)*c1^c2  (c1>0)
329  *  - ^(*(x,c1),c2) -> ^(-x,c2)*c1^c2  (c1<0)
330  *
331  *  @param level cut-off in recursive evaluation */
332 ex power::eval(int level) const
333 {
334         if ((level==1) && (flags & status_flags::evaluated))
335                 return *this;
336         else if (level == -max_recursion_level)
337                 throw(std::runtime_error("max recursion level reached"));
338         
339         const ex & ebasis    = level==1 ? basis    : basis.eval(level-1);
340         const ex & eexponent = level==1 ? exponent : exponent.eval(level-1);
341         
342         bool basis_is_numerical = false;
343         bool exponent_is_numerical = false;
344         const numeric *num_basis;
345         const numeric *num_exponent;
346         
347         if (is_exactly_a<numeric>(ebasis)) {
348                 basis_is_numerical = true;
349                 num_basis = &ex_to<numeric>(ebasis);
350         }
351         if (is_exactly_a<numeric>(eexponent)) {
352                 exponent_is_numerical = true;
353                 num_exponent = &ex_to<numeric>(eexponent);
354         }
355         
356         // ^(x,0) -> 1  (0^0 also handled here)
357         if (eexponent.is_zero()) {
358                 if (ebasis.is_zero())
359                         throw (std::domain_error("power::eval(): pow(0,0) is undefined"));
360                 else
361                         return _ex1;
362         }
363         
364         // ^(x,1) -> x
365         if (eexponent.is_equal(_ex1))
366                 return ebasis;
367
368         // ^(0,c1) -> 0 or exception  (depending on real value of c1)
369         if (ebasis.is_zero() && exponent_is_numerical) {
370                 if ((num_exponent->real()).is_zero())
371                         throw (std::domain_error("power::eval(): pow(0,I) is undefined"));
372                 else if ((num_exponent->real()).is_negative())
373                         throw (pole_error("power::eval(): division by zero",1));
374                 else
375                         return _ex0;
376         }
377
378         // ^(1,x) -> 1
379         if (ebasis.is_equal(_ex1))
380                 return _ex1;
381
382         if (exponent_is_numerical) {
383
384                 // ^(c1,c2) -> c1^c2  (c1, c2 numeric(),
385                 // except if c1,c2 are rational, but c1^c2 is not)
386                 if (basis_is_numerical) {
387                         const bool basis_is_crational = num_basis->is_crational();
388                         const bool exponent_is_crational = num_exponent->is_crational();
389                         if (!basis_is_crational || !exponent_is_crational) {
390                                 // return a plain float
391                                 return (new numeric(num_basis->power(*num_exponent)))->setflag(status_flags::dynallocated |
392                                                                                                status_flags::evaluated |
393                                                                                                status_flags::expanded);
394                         }
395
396                         const numeric res = num_basis->power(*num_exponent);
397                         if (res.is_crational()) {
398                                 return res;
399                         }
400                         GINAC_ASSERT(!num_exponent->is_integer());  // has been handled by now
401
402                         // ^(c1,n/m) -> *(c1^q,c1^(n/m-q)), 0<(n/m-q)<1, q integer
403                         if (basis_is_crational && exponent_is_crational
404                             && num_exponent->is_real()
405                             && !num_exponent->is_integer()) {
406                                 const numeric n = num_exponent->numer();
407                                 const numeric m = num_exponent->denom();
408                                 numeric r;
409                                 numeric q = iquo(n, m, r);
410                                 if (r.is_negative()) {
411                                         r += m;
412                                         --q;
413                                 }
414                                 if (q.is_zero()) {  // the exponent was in the allowed range 0<(n/m)<1
415                                         if (num_basis->is_rational() && !num_basis->is_integer()) {
416                                                 // try it for numerator and denominator separately, in order to
417                                                 // partially simplify things like (5/8)^(1/3) -> 1/2*5^(1/3)
418                                                 const numeric bnum = num_basis->numer();
419                                                 const numeric bden = num_basis->denom();
420                                                 const numeric res_bnum = bnum.power(*num_exponent);
421                                                 const numeric res_bden = bden.power(*num_exponent);
422                                                 if (res_bnum.is_integer())
423                                                         return (new mul(power(bden,-*num_exponent),res_bnum))->setflag(status_flags::dynallocated | status_flags::evaluated);
424                                                 if (res_bden.is_integer())
425                                                         return (new mul(power(bnum,*num_exponent),res_bden.inverse()))->setflag(status_flags::dynallocated | status_flags::evaluated);
426                                         }
427                                         return this->hold();
428                                 } else {
429                                         // assemble resulting product, but allowing for a re-evaluation,
430                                         // because otherwise we'll end up with something like
431                                         //    (7/8)^(4/3)  ->  7/8*(1/2*7^(1/3))
432                                         // instead of 7/16*7^(1/3).
433                                         ex prod = power(*num_basis,r.div(m));
434                                         return prod*power(*num_basis,q);
435                                 }
436                         }
437                 }
438         
439                 // ^(^(x,c1),c2) -> ^(x,c1*c2)
440                 // (c1, c2 numeric(), c2 integer or -1 < c1 <= 1,
441                 // case c1==1 should not happen, see below!)
442                 if (is_exactly_a<power>(ebasis)) {
443                         const power & sub_power = ex_to<power>(ebasis);
444                         const ex & sub_basis = sub_power.basis;
445                         const ex & sub_exponent = sub_power.exponent;
446                         if (is_exactly_a<numeric>(sub_exponent)) {
447                                 const numeric & num_sub_exponent = ex_to<numeric>(sub_exponent);
448                                 GINAC_ASSERT(num_sub_exponent!=numeric(1));
449                                 if (num_exponent->is_integer() || (abs(num_sub_exponent) - _num1).is_negative())
450                                         return power(sub_basis,num_sub_exponent.mul(*num_exponent));
451                         }
452                 }
453         
454                 // ^(*(x,y,z),c1) -> *(x^c1,y^c1,z^c1) (c1 integer)
455                 if (num_exponent->is_integer() && is_exactly_a<mul>(ebasis)) {
456                         return expand_mul(ex_to<mul>(ebasis), *num_exponent, 0);
457                 }
458         
459                 // ^(*(...,x;c1),c2) -> *(^(*(...,x;1),c2),c1^c2)  (c1, c2 numeric(), c1>0)
460                 // ^(*(...,x;c1),c2) -> *(^(*(...,x;-1),c2),(-c1)^c2)  (c1, c2 numeric(), c1<0)
461                 if (is_exactly_a<mul>(ebasis)) {
462                         GINAC_ASSERT(!num_exponent->is_integer()); // should have been handled above
463                         const mul & mulref = ex_to<mul>(ebasis);
464                         if (!mulref.overall_coeff.is_equal(_ex1)) {
465                                 const numeric & num_coeff = ex_to<numeric>(mulref.overall_coeff);
466                                 if (num_coeff.is_real()) {
467                                         if (num_coeff.is_positive()) {
468                                                 mul *mulp = new mul(mulref);
469                                                 mulp->overall_coeff = _ex1;
470                                                 mulp->clearflag(status_flags::evaluated);
471                                                 mulp->clearflag(status_flags::hash_calculated);
472                                                 return (new mul(power(*mulp,exponent),
473                                                                 power(num_coeff,*num_exponent)))->setflag(status_flags::dynallocated);
474                                         } else {
475                                                 GINAC_ASSERT(num_coeff.compare(_num0)<0);
476                                                 if (!num_coeff.is_equal(_num_1)) {
477                                                         mul *mulp = new mul(mulref);
478                                                         mulp->overall_coeff = _ex_1;
479                                                         mulp->clearflag(status_flags::evaluated);
480                                                         mulp->clearflag(status_flags::hash_calculated);
481                                                         return (new mul(power(*mulp,exponent),
482                                                                         power(abs(num_coeff),*num_exponent)))->setflag(status_flags::dynallocated);
483                                                 }
484                                         }
485                                 }
486                         }
487                 }
488
489                 // ^(nc,c1) -> ncmul(nc,nc,...) (c1 positive integer, unless nc is a matrix)
490                 if (num_exponent->is_pos_integer() &&
491                     ebasis.return_type() != return_types::commutative &&
492                     !is_a<matrix>(ebasis)) {
493                         return ncmul(exvector(num_exponent->to_int(), ebasis), true);
494                 }
495         }
496         
497         if (are_ex_trivially_equal(ebasis,basis) &&
498             are_ex_trivially_equal(eexponent,exponent)) {
499                 return this->hold();
500         }
501         return (new power(ebasis, eexponent))->setflag(status_flags::dynallocated |
502                                                        status_flags::evaluated);
503 }
504
505 ex power::evalf(int level) const
506 {
507         ex ebasis;
508         ex eexponent;
509         
510         if (level==1) {
511                 ebasis = basis;
512                 eexponent = exponent;
513         } else if (level == -max_recursion_level) {
514                 throw(std::runtime_error("max recursion level reached"));
515         } else {
516                 ebasis = basis.evalf(level-1);
517                 if (!is_exactly_a<numeric>(exponent))
518                         eexponent = exponent.evalf(level-1);
519                 else
520                         eexponent = exponent;
521         }
522
523         return power(ebasis,eexponent);
524 }
525
526 ex power::evalm() const
527 {
528         const ex ebasis = basis.evalm();
529         const ex eexponent = exponent.evalm();
530         if (is_a<matrix>(ebasis)) {
531                 if (is_exactly_a<numeric>(eexponent)) {
532                         return (new matrix(ex_to<matrix>(ebasis).pow(eexponent)))->setflag(status_flags::dynallocated);
533                 }
534         }
535         return (new power(ebasis, eexponent))->setflag(status_flags::dynallocated);
536 }
537
538 // from mul.cpp
539 extern bool tryfactsubs(const ex &, const ex &, int &, lst &);
540
541 ex power::subs(const exmap & m, unsigned options) const
542 {       
543         const ex &subsed_basis = basis.subs(m, options);
544         const ex &subsed_exponent = exponent.subs(m, options);
545
546         if (!are_ex_trivially_equal(basis, subsed_basis)
547          || !are_ex_trivially_equal(exponent, subsed_exponent)) 
548                 return power(subsed_basis, subsed_exponent).subs_one_level(m, options);
549
550         if (!(options & subs_options::algebraic))
551                 return subs_one_level(m, options);
552
553         for (exmap::const_iterator it = m.begin(); it != m.end(); ++it) {
554                 int nummatches = std::numeric_limits<int>::max();
555                 lst repls;
556                 if (tryfactsubs(*this, it->first, nummatches, repls))
557                         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);
558         }
559
560         return subs_one_level(m, options);
561 }
562
563 ex power::eval_ncmul(const exvector & v) const
564 {
565         return inherited::eval_ncmul(v);
566 }
567
568 ex power::conjugate() const
569 {
570         ex newbasis = basis.conjugate();
571         ex newexponent = exponent.conjugate();
572         if (are_ex_trivially_equal(basis, newbasis) && are_ex_trivially_equal(exponent, newexponent)) {
573                 return *this;
574         }
575         return (new power(newbasis, newexponent))->setflag(status_flags::dynallocated);
576 }
577
578 // protected
579
580 /** Implementation of ex::diff() for a power.
581  *  @see ex::diff */
582 ex power::derivative(const symbol & s) const
583 {
584         if (exponent.info(info_flags::real)) {
585                 // D(b^r) = r * b^(r-1) * D(b) (faster than the formula below)
586                 epvector newseq;
587                 newseq.reserve(2);
588                 newseq.push_back(expair(basis, exponent - _ex1));
589                 newseq.push_back(expair(basis.diff(s), _ex1));
590                 return mul(newseq, exponent);
591         } else {
592                 // D(b^e) = b^e * (D(e)*ln(b) + e*D(b)/b)
593                 return mul(*this,
594                            add(mul(exponent.diff(s), log(basis)),
595                            mul(mul(exponent, basis.diff(s)), power(basis, _ex_1))));
596         }
597 }
598
599 int power::compare_same_type(const basic & other) const
600 {
601         GINAC_ASSERT(is_exactly_a<power>(other));
602         const power &o = static_cast<const power &>(other);
603
604         int cmpval = basis.compare(o.basis);
605         if (cmpval)
606                 return cmpval;
607         else
608                 return exponent.compare(o.exponent);
609 }
610
611 unsigned power::return_type() const
612 {
613         return basis.return_type();
614 }
615    
616 unsigned power::return_type_tinfo() const
617 {
618         return basis.return_type_tinfo();
619 }
620
621 ex power::expand(unsigned options) const
622 {
623         if (options == 0 && (flags & status_flags::expanded))
624                 return *this;
625         
626         const ex expanded_basis = basis.expand(options);
627         const ex expanded_exponent = exponent.expand(options);
628         
629         // x^(a+b) -> x^a * x^b
630         if (is_exactly_a<add>(expanded_exponent)) {
631                 const add &a = ex_to<add>(expanded_exponent);
632                 exvector distrseq;
633                 distrseq.reserve(a.seq.size() + 1);
634                 epvector::const_iterator last = a.seq.end();
635                 epvector::const_iterator cit = a.seq.begin();
636                 while (cit!=last) {
637                         distrseq.push_back(power(expanded_basis, a.recombine_pair_to_ex(*cit)));
638                         ++cit;
639                 }
640                 
641                 // Make sure that e.g. (x+y)^(2+a) expands the (x+y)^2 factor
642                 if (ex_to<numeric>(a.overall_coeff).is_integer()) {
643                         const numeric &num_exponent = ex_to<numeric>(a.overall_coeff);
644                         int int_exponent = num_exponent.to_int();
645                         if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
646                                 distrseq.push_back(expand_add(ex_to<add>(expanded_basis), int_exponent, options));
647                         else
648                                 distrseq.push_back(power(expanded_basis, a.overall_coeff));
649                 } else
650                         distrseq.push_back(power(expanded_basis, a.overall_coeff));
651                 
652                 // Make sure that e.g. (x+y)^(1+a) -> x*(x+y)^a + y*(x+y)^a
653                 ex r = (new mul(distrseq))->setflag(status_flags::dynallocated);
654                 return r.expand(options);
655         }
656         
657         if (!is_exactly_a<numeric>(expanded_exponent) ||
658                 !ex_to<numeric>(expanded_exponent).is_integer()) {
659                 if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent)) {
660                         return this->hold();
661                 } else {
662                         return (new power(expanded_basis,expanded_exponent))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
663                 }
664         }
665         
666         // integer numeric exponent
667         const numeric & num_exponent = ex_to<numeric>(expanded_exponent);
668         int int_exponent = num_exponent.to_int();
669         
670         // (x+y)^n, n>0
671         if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
672                 return expand_add(ex_to<add>(expanded_basis), int_exponent, options);
673         
674         // (x*y)^n -> x^n * y^n
675         if (is_exactly_a<mul>(expanded_basis))
676                 return expand_mul(ex_to<mul>(expanded_basis), num_exponent, options, true);
677         
678         // cannot expand further
679         if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent))
680                 return this->hold();
681         else
682                 return (new power(expanded_basis,expanded_exponent))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
683 }
684
685 //////////
686 // new virtual functions which can be overridden by derived classes
687 //////////
688
689 // none
690
691 //////////
692 // non-virtual functions in this class
693 //////////
694
695 /** expand a^n where a is an add and n is a positive integer.
696  *  @see power::expand */
697 ex power::expand_add(const add & a, int n, unsigned options) const
698 {
699         if (n==2)
700                 return expand_add_2(a, options);
701
702         const size_t m = a.nops();
703         exvector result;
704         // The number of terms will be the number of combinatorial compositions,
705         // i.e. the number of unordered arrangement of m nonnegative integers
706         // which sum up to n.  It is frequently written as C_n(m) and directly
707         // related with binomial coefficients:
708         result.reserve(binomial(numeric(n+m-1), numeric(m-1)).to_int());
709         intvector k(m-1);
710         intvector k_cum(m-1); // k_cum[l]:=sum(i=0,l,k[l]);
711         intvector upper_limit(m-1);
712         int l;
713
714         for (size_t l=0; l<m-1; ++l) {
715                 k[l] = 0;
716                 k_cum[l] = 0;
717                 upper_limit[l] = n;
718         }
719
720         while (true) {
721                 exvector term;
722                 term.reserve(m+1);
723                 for (l=0; l<m-1; ++l) {
724                         const ex & b = a.op(l);
725                         GINAC_ASSERT(!is_exactly_a<add>(b));
726                         GINAC_ASSERT(!is_exactly_a<power>(b) ||
727                                      !is_exactly_a<numeric>(ex_to<power>(b).exponent) ||
728                                      !ex_to<numeric>(ex_to<power>(b).exponent).is_pos_integer() ||
729                                      !is_exactly_a<add>(ex_to<power>(b).basis) ||
730                                      !is_exactly_a<mul>(ex_to<power>(b).basis) ||
731                                      !is_exactly_a<power>(ex_to<power>(b).basis));
732                         if (is_exactly_a<mul>(b))
733                                 term.push_back(expand_mul(ex_to<mul>(b), numeric(k[l]), options, true));
734                         else
735                                 term.push_back(power(b,k[l]));
736                 }
737
738                 const ex & b = a.op(l);
739                 GINAC_ASSERT(!is_exactly_a<add>(b));
740                 GINAC_ASSERT(!is_exactly_a<power>(b) ||
741                              !is_exactly_a<numeric>(ex_to<power>(b).exponent) ||
742                              !ex_to<numeric>(ex_to<power>(b).exponent).is_pos_integer() ||
743                              !is_exactly_a<add>(ex_to<power>(b).basis) ||
744                              !is_exactly_a<mul>(ex_to<power>(b).basis) ||
745                              !is_exactly_a<power>(ex_to<power>(b).basis));
746                 if (is_exactly_a<mul>(b))
747                         term.push_back(expand_mul(ex_to<mul>(b), numeric(n-k_cum[m-2]), options, true));
748                 else
749                         term.push_back(power(b,n-k_cum[m-2]));
750
751                 numeric f = binomial(numeric(n),numeric(k[0]));
752                 for (l=1; l<m-1; ++l)
753                         f *= binomial(numeric(n-k_cum[l-1]),numeric(k[l]));
754
755                 term.push_back(f);
756
757                 result.push_back(ex((new mul(term))->setflag(status_flags::dynallocated)).expand(options));
758
759                 // increment k[]
760                 l = m-2;
761                 while ((l>=0) && ((++k[l])>upper_limit[l])) {
762                         k[l] = 0;
763                         --l;
764                 }
765                 if (l<0) break;
766
767                 // recalc k_cum[] and upper_limit[]
768                 k_cum[l] = (l==0 ? k[0] : k_cum[l-1]+k[l]);
769
770                 for (size_t i=l+1; i<m-1; ++i)
771                         k_cum[i] = k_cum[i-1]+k[i];
772
773                 for (size_t i=l+1; i<m-1; ++i)
774                         upper_limit[i] = n-k_cum[i-1];
775         }
776
777         return (new add(result))->setflag(status_flags::dynallocated |
778                                           status_flags::expanded);
779 }
780
781
782 /** Special case of power::expand_add. Expands a^2 where a is an add.
783  *  @see power::expand_add */
784 ex power::expand_add_2(const add & a, unsigned options) const
785 {
786         epvector sum;
787         size_t a_nops = a.nops();
788         sum.reserve((a_nops*(a_nops+1))/2);
789         epvector::const_iterator last = a.seq.end();
790
791         // power(+(x,...,z;c),2)=power(+(x,...,z;0),2)+2*c*+(x,...,z;0)+c*c
792         // first part: ignore overall_coeff and expand other terms
793         for (epvector::const_iterator cit0=a.seq.begin(); cit0!=last; ++cit0) {
794                 const ex & r = cit0->rest;
795                 const ex & c = cit0->coeff;
796                 
797                 GINAC_ASSERT(!is_exactly_a<add>(r));
798                 GINAC_ASSERT(!is_exactly_a<power>(r) ||
799                              !is_exactly_a<numeric>(ex_to<power>(r).exponent) ||
800                              !ex_to<numeric>(ex_to<power>(r).exponent).is_pos_integer() ||
801                              !is_exactly_a<add>(ex_to<power>(r).basis) ||
802                              !is_exactly_a<mul>(ex_to<power>(r).basis) ||
803                              !is_exactly_a<power>(ex_to<power>(r).basis));
804                 
805                 if (c.is_equal(_ex1)) {
806                         if (is_exactly_a<mul>(r)) {
807                                 sum.push_back(expair(expand_mul(ex_to<mul>(r), _num2, options, true),
808                                                      _ex1));
809                         } else {
810                                 sum.push_back(expair((new power(r,_ex2))->setflag(status_flags::dynallocated),
811                                                      _ex1));
812                         }
813                 } else {
814                         if (is_exactly_a<mul>(r)) {
815                                 sum.push_back(a.combine_ex_with_coeff_to_pair(expand_mul(ex_to<mul>(r), _num2, options, true),
816                                                      ex_to<numeric>(c).power_dyn(_num2)));
817                         } else {
818                                 sum.push_back(a.combine_ex_with_coeff_to_pair((new power(r,_ex2))->setflag(status_flags::dynallocated),
819                                                      ex_to<numeric>(c).power_dyn(_num2)));
820                         }
821                 }
822
823                 for (epvector::const_iterator cit1=cit0+1; cit1!=last; ++cit1) {
824                         const ex & r1 = cit1->rest;
825                         const ex & c1 = cit1->coeff;
826                         sum.push_back(a.combine_ex_with_coeff_to_pair((new mul(r,r1))->setflag(status_flags::dynallocated),
827                                                                       _num2.mul(ex_to<numeric>(c)).mul_dyn(ex_to<numeric>(c1))));
828                 }
829         }
830         
831         GINAC_ASSERT(sum.size()==(a.seq.size()*(a.seq.size()+1))/2);
832         
833         // second part: add terms coming from overall_factor (if != 0)
834         if (!a.overall_coeff.is_zero()) {
835                 epvector::const_iterator i = a.seq.begin(), end = a.seq.end();
836                 while (i != end) {
837                         sum.push_back(a.combine_pair_with_coeff_to_pair(*i, ex_to<numeric>(a.overall_coeff).mul_dyn(_num2)));
838                         ++i;
839                 }
840                 sum.push_back(expair(ex_to<numeric>(a.overall_coeff).power_dyn(_num2),_ex1));
841         }
842         
843         GINAC_ASSERT(sum.size()==(a_nops*(a_nops+1))/2);
844         
845         return (new add(sum))->setflag(status_flags::dynallocated | status_flags::expanded);
846 }
847
848 /** Expand factors of m in m^n where m is a mul and n is and integer.
849  *  @see power::expand */
850 ex power::expand_mul(const mul & m, const numeric & n, unsigned options, bool from_expand) const
851 {
852         GINAC_ASSERT(n.is_integer());
853
854         if (n.is_zero())
855                 return _ex1;
856
857         epvector distrseq;
858         distrseq.reserve(m.seq.size());
859         bool need_reexpand = false;
860
861         epvector::const_iterator last = m.seq.end();
862         epvector::const_iterator cit = m.seq.begin();
863         while (cit!=last) {
864                 if (is_exactly_a<numeric>(cit->rest)) {
865                         distrseq.push_back(m.combine_pair_with_coeff_to_pair(*cit, n));
866                 } else {
867                         // it is safe not to call mul::combine_pair_with_coeff_to_pair()
868                         // since n is an integer
869                         numeric new_coeff = ex_to<numeric>(cit->coeff).mul(n);
870                         if (from_expand && is_exactly_a<add>(cit->rest) && new_coeff.is_pos_integer()) {
871                                 // this happens when e.g. (a+b)^(1/2) gets squared and
872                                 // the resulting product needs to be reexpanded
873                                 need_reexpand = true;
874                         }
875                         distrseq.push_back(expair(cit->rest, new_coeff));
876                 }
877                 ++cit;
878         }
879
880         const mul & result = static_cast<const mul &>((new mul(distrseq, ex_to<numeric>(m.overall_coeff).power_dyn(n)))->setflag(status_flags::dynallocated));
881         if (need_reexpand)
882                 return ex(result).expand(options);
883         if (from_expand)
884                 return result.setflag(status_flags::expanded);
885         return result;
886 }
887
888 } // namespace GiNaC