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