1bd122b8767c6a31c1dedcdf09689425ff2b7021
[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-2011 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
46 namespace GiNaC {
47
48 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(power, basic,
49   print_func<print_dflt>(&power::do_print_dflt).
50   print_func<print_latex>(&power::do_print_latex).
51   print_func<print_csrc>(&power::do_print_csrc).
52   print_func<print_python>(&power::do_print_python).
53   print_func<print_python_repr>(&power::do_print_python_repr).
54   print_func<print_csrc_cl_N>(&power::do_print_csrc_cl_N))
55
56 typedef std::vector<int> intvector;
57
58 //////////
59 // default constructor
60 //////////
61
62 power::power() { }
63
64 //////////
65 // other constructors
66 //////////
67
68 // all inlined
69
70 //////////
71 // archiving
72 //////////
73
74 void power::read_archive(const archive_node &n, lst &sym_lst)
75 {
76         inherited::read_archive(n, sym_lst);
77         n.find_ex("basis", basis, sym_lst);
78         n.find_ex("exponent", exponent, sym_lst);
79 }
80
81 void power::archive(archive_node &n) const
82 {
83         inherited::archive(n);
84         n.add_ex("basis", basis);
85         n.add_ex("exponent", exponent);
86 }
87
88 //////////
89 // functions overriding virtual functions from base classes
90 //////////
91
92 // public
93
94 void power::print_power(const print_context & c, const char *powersymbol, const char *openbrace, const char *closebrace, unsigned level) const
95 {
96         // Ordinary output of powers using '^' or '**'
97         if (precedence() <= level)
98                 c.s << openbrace << '(';
99         basis.print(c, precedence());
100         c.s << powersymbol;
101         c.s << openbrace;
102         exponent.print(c, precedence());
103         c.s << closebrace;
104         if (precedence() <= level)
105                 c.s << ')' << closebrace;
106 }
107
108 void power::do_print_dflt(const print_dflt & c, unsigned level) const
109 {
110         if (exponent.is_equal(_ex1_2)) {
111
112                 // Square roots are printed in a special way
113                 c.s << "sqrt(";
114                 basis.print(c);
115                 c.s << ')';
116
117         } else
118                 print_power(c, "^", "", "", level);
119 }
120
121 void power::do_print_latex(const print_latex & c, unsigned level) const
122 {
123         if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_negative()) {
124
125                 // Powers with negative numeric exponents are printed as fractions
126                 c.s << "\\frac{1}{";
127                 power(basis, -exponent).eval().print(c);
128                 c.s << '}';
129
130         } else if (exponent.is_equal(_ex1_2)) {
131
132                 // Square roots are printed in a special way
133                 c.s << "\\sqrt{";
134                 basis.print(c);
135                 c.s << '}';
136
137         } else
138                 print_power(c, "^", "{", "}", level);
139 }
140
141 static void print_sym_pow(const print_context & c, const symbol &x, int exp)
142 {
143         // Optimal output of integer powers of symbols to aid compiler CSE.
144         // C.f. ISO/IEC 14882:1998, section 1.9 [intro execution], paragraph 15
145         // to learn why such a parenthesation is really necessary.
146         if (exp == 1) {
147                 x.print(c);
148         } else if (exp == 2) {
149                 x.print(c);
150                 c.s << "*";
151                 x.print(c);
152         } else if (exp & 1) {
153                 x.print(c);
154                 c.s << "*";
155                 print_sym_pow(c, x, exp-1);
156         } else {
157                 c.s << "(";
158                 print_sym_pow(c, x, exp >> 1);
159                 c.s << ")*(";
160                 print_sym_pow(c, x, exp >> 1);
161                 c.s << ")";
162         }
163 }
164
165 void power::do_print_csrc_cl_N(const print_csrc_cl_N& c, unsigned level) const
166 {
167         if (exponent.is_equal(_ex_1)) {
168                 c.s << "recip(";
169                 basis.print(c);
170                 c.s << ')';
171                 return;
172         }
173         c.s << "expt(";
174         basis.print(c);
175         c.s << ", ";
176         exponent.print(c);
177         c.s << ')';
178 }
179
180 void power::do_print_csrc(const print_csrc & c, unsigned level) const
181 {
182         // Integer powers of symbols are printed in a special, optimized way
183         if (exponent.info(info_flags::integer)
184          && (is_a<symbol>(basis) || is_a<constant>(basis))) {
185                 int exp = ex_to<numeric>(exponent).to_int();
186                 if (exp > 0)
187                         c.s << '(';
188                 else {
189                         exp = -exp;
190                         c.s << "1.0/(";
191                 }
192                 print_sym_pow(c, ex_to<symbol>(basis), exp);
193                 c.s << ')';
194
195         // <expr>^-1 is printed as "1.0/<expr>" or with the recip() function of CLN
196         } else if (exponent.is_equal(_ex_1)) {
197                 c.s << "1.0/(";
198                 basis.print(c);
199                 c.s << ')';
200
201         // Otherwise, use the pow() function
202         } else {
203                 c.s << "pow(";
204                 basis.print(c);
205                 c.s << ',';
206                 exponent.print(c);
207                 c.s << ')';
208         }
209 }
210
211 void power::do_print_python(const print_python & c, unsigned level) const
212 {
213         print_power(c, "**", "", "", level);
214 }
215
216 void power::do_print_python_repr(const print_python_repr & c, unsigned level) const
217 {
218         c.s << class_name() << '(';
219         basis.print(c);
220         c.s << ',';
221         exponent.print(c);
222         c.s << ')';
223 }
224
225 bool power::info(unsigned inf) const
226 {
227         switch (inf) {
228                 case info_flags::polynomial:
229                 case info_flags::integer_polynomial:
230                 case info_flags::cinteger_polynomial:
231                 case info_flags::rational_polynomial:
232                 case info_flags::crational_polynomial:
233                         return exponent.info(info_flags::nonnegint) &&
234                                basis.info(inf);
235                 case info_flags::rational_function:
236                         return exponent.info(info_flags::integer) &&
237                                basis.info(inf);
238                 case info_flags::algebraic:
239                         return !exponent.info(info_flags::integer) ||
240                                basis.info(inf);
241                 case info_flags::expanded:
242                         return (flags & status_flags::expanded);
243                 case info_flags::positive:
244                         return basis.info(info_flags::positive) && exponent.info(info_flags::real);
245                 case info_flags::nonnegative:
246                         return 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).to_int()
632                                         > ex_to<numeric>(other.op(1)).to_int()
633                         && basis.match(other.op(0)))
634                 return true;
635         if (exponent.info(info_flags::negint)
636                         && other.op(1).info(info_flags::negint)
637                         && ex_to<numeric>(exponent).to_int()
638                                         < ex_to<numeric>(other.op(1)).to_int()
639                         && basis.match(other.op(0)))
640                 return true;
641         return basic::has(other, options);
642 }
643
644 // from mul.cpp
645 extern bool tryfactsubs(const ex &, const ex &, int &, exmap&);
646
647 ex power::subs(const exmap & m, unsigned options) const
648 {       
649         const ex &subsed_basis = basis.subs(m, options);
650         const ex &subsed_exponent = exponent.subs(m, options);
651
652         if (!are_ex_trivially_equal(basis, subsed_basis)
653          || !are_ex_trivially_equal(exponent, subsed_exponent)) 
654                 return power(subsed_basis, subsed_exponent).subs_one_level(m, options);
655
656         if (!(options & subs_options::algebraic))
657                 return subs_one_level(m, options);
658
659         for (exmap::const_iterator it = m.begin(); it != m.end(); ++it) {
660                 int nummatches = std::numeric_limits<int>::max();
661                 exmap repls;
662                 if (tryfactsubs(*this, it->first, nummatches, repls)) {
663                         ex anum = it->second.subs(repls, subs_options::no_pattern);
664                         ex aden = it->first.subs(repls, subs_options::no_pattern);
665                         ex result = (*this)*power(anum/aden, nummatches);
666                         return (ex_to<basic>(result)).subs_one_level(m, options);
667                 }
668         }
669
670         return subs_one_level(m, options);
671 }
672
673 ex power::eval_ncmul(const exvector & v) const
674 {
675         return inherited::eval_ncmul(v);
676 }
677
678 ex power::conjugate() const
679 {
680         // conjugate(pow(x,y))==pow(conjugate(x),conjugate(y)) unless on the
681         // branch cut which runs along the negative real axis.
682         if (basis.info(info_flags::positive)) {
683                 ex newexponent = exponent.conjugate();
684                 if (are_ex_trivially_equal(exponent, newexponent)) {
685                         return *this;
686                 }
687                 return (new power(basis, newexponent))->setflag(status_flags::dynallocated);
688         }
689         if (exponent.info(info_flags::integer)) {
690                 ex newbasis = basis.conjugate();
691                 if (are_ex_trivially_equal(basis, newbasis)) {
692                         return *this;
693                 }
694                 return (new power(newbasis, exponent))->setflag(status_flags::dynallocated);
695         }
696         return conjugate_function(*this).hold();
697 }
698
699 ex power::real_part() const
700 {
701         if (exponent.info(info_flags::integer)) {
702                 ex basis_real = basis.real_part();
703                 if (basis_real == basis)
704                         return *this;
705                 realsymbol a("a"),b("b");
706                 ex result;
707                 if (exponent.info(info_flags::posint))
708                         result = power(a+I*b,exponent);
709                 else
710                         result = power(a/(a*a+b*b)-I*b/(a*a+b*b),-exponent);
711                 result = result.expand();
712                 result = result.real_part();
713                 result = result.subs(lst( a==basis_real, b==basis.imag_part() ));
714                 return result;
715         }
716         
717         ex a = basis.real_part();
718         ex b = basis.imag_part();
719         ex c = exponent.real_part();
720         ex d = exponent.imag_part();
721         return power(abs(basis),c)*exp(-d*atan2(b,a))*cos(c*atan2(b,a)+d*log(abs(basis)));
722 }
723
724 ex power::imag_part() const
725 {
726         if (exponent.info(info_flags::integer)) {
727                 ex basis_real = basis.real_part();
728                 if (basis_real == basis)
729                         return 0;
730                 realsymbol a("a"),b("b");
731                 ex result;
732                 if (exponent.info(info_flags::posint))
733                         result = power(a+I*b,exponent);
734                 else
735                         result = power(a/(a*a+b*b)-I*b/(a*a+b*b),-exponent);
736                 result = result.expand();
737                 result = result.imag_part();
738                 result = result.subs(lst( a==basis_real, b==basis.imag_part() ));
739                 return result;
740         }
741         
742         ex a=basis.real_part();
743         ex b=basis.imag_part();
744         ex c=exponent.real_part();
745         ex d=exponent.imag_part();
746         return power(abs(basis),c)*exp(-d*atan2(b,a))*sin(c*atan2(b,a)+d*log(abs(basis)));
747 }
748
749 // protected
750
751 // protected
752
753 /** Implementation of ex::diff() for a power.
754  *  @see ex::diff */
755 ex power::derivative(const symbol & s) const
756 {
757         if (is_a<numeric>(exponent)) {
758                 // D(b^r) = r * b^(r-1) * D(b) (faster than the formula below)
759                 epvector newseq;
760                 newseq.reserve(2);
761                 newseq.push_back(expair(basis, exponent - _ex1));
762                 newseq.push_back(expair(basis.diff(s), _ex1));
763                 return mul(newseq, exponent);
764         } else {
765                 // D(b^e) = b^e * (D(e)*ln(b) + e*D(b)/b)
766                 return mul(*this,
767                            add(mul(exponent.diff(s), log(basis)),
768                            mul(mul(exponent, basis.diff(s)), power(basis, _ex_1))));
769         }
770 }
771
772 int power::compare_same_type(const basic & other) const
773 {
774         GINAC_ASSERT(is_exactly_a<power>(other));
775         const power &o = static_cast<const power &>(other);
776
777         int cmpval = basis.compare(o.basis);
778         if (cmpval)
779                 return cmpval;
780         else
781                 return exponent.compare(o.exponent);
782 }
783
784 unsigned power::return_type() const
785 {
786         return basis.return_type();
787 }
788
789 return_type_t power::return_type_tinfo() const
790 {
791         return basis.return_type_tinfo();
792 }
793
794 ex power::expand(unsigned options) const
795 {
796         if (is_a<symbol>(basis) && exponent.info(info_flags::integer)) {
797                 // A special case worth optimizing.
798                 setflag(status_flags::expanded);
799                 return *this;
800         }
801
802         const ex expanded_basis = basis.expand(options);
803         const ex expanded_exponent = exponent.expand(options);
804         
805         // x^(a+b) -> x^a * x^b
806         if (is_exactly_a<add>(expanded_exponent)) {
807                 const add &a = ex_to<add>(expanded_exponent);
808                 exvector distrseq;
809                 distrseq.reserve(a.seq.size() + 1);
810                 epvector::const_iterator last = a.seq.end();
811                 epvector::const_iterator cit = a.seq.begin();
812                 while (cit!=last) {
813                         distrseq.push_back(power(expanded_basis, a.recombine_pair_to_ex(*cit)));
814                         ++cit;
815                 }
816                 
817                 // Make sure that e.g. (x+y)^(2+a) expands the (x+y)^2 factor
818                 if (ex_to<numeric>(a.overall_coeff).is_integer()) {
819                         const numeric &num_exponent = ex_to<numeric>(a.overall_coeff);
820                         int int_exponent = num_exponent.to_int();
821                         if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
822                                 distrseq.push_back(expand_add(ex_to<add>(expanded_basis), int_exponent, options));
823                         else
824                                 distrseq.push_back(power(expanded_basis, a.overall_coeff));
825                 } else
826                         distrseq.push_back(power(expanded_basis, a.overall_coeff));
827                 
828                 // Make sure that e.g. (x+y)^(1+a) -> x*(x+y)^a + y*(x+y)^a
829                 ex r = (new mul(distrseq))->setflag(status_flags::dynallocated);
830                 return r.expand(options);
831         }
832         
833         if (!is_exactly_a<numeric>(expanded_exponent) ||
834                 !ex_to<numeric>(expanded_exponent).is_integer()) {
835                 if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent)) {
836                         return this->hold();
837                 } else {
838                         return (new power(expanded_basis,expanded_exponent))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
839                 }
840         }
841         
842         // integer numeric exponent
843         const numeric & num_exponent = ex_to<numeric>(expanded_exponent);
844         int int_exponent = num_exponent.to_int();
845         
846         // (x+y)^n, n>0
847         if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
848                 return expand_add(ex_to<add>(expanded_basis), int_exponent, options);
849         
850         // (x*y)^n -> x^n * y^n
851         if (is_exactly_a<mul>(expanded_basis))
852                 return expand_mul(ex_to<mul>(expanded_basis), num_exponent, options, true);
853         
854         // cannot expand further
855         if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent))
856                 return this->hold();
857         else
858                 return (new power(expanded_basis,expanded_exponent))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
859 }
860
861 //////////
862 // new virtual functions which can be overridden by derived classes
863 //////////
864
865 // none
866
867 //////////
868 // non-virtual functions in this class
869 //////////
870
871 /** expand a^n where a is an add and n is a positive integer.
872  *  @see power::expand */
873 ex power::expand_add(const add & a, int n, unsigned options) const
874 {
875         if (n==2)
876                 return expand_add_2(a, options);
877
878         const size_t m = a.nops();
879         exvector result;
880         // The number of terms will be the number of combinatorial compositions,
881         // i.e. the number of unordered arrangements of m nonnegative integers
882         // which sum up to n.  It is frequently written as C_n(m) and directly
883         // related with binomial coefficients:
884         result.reserve(binomial(numeric(n+m-1), numeric(m-1)).to_int());
885         intvector k(m-1);
886         intvector k_cum(m-1); // k_cum[l]:=sum(i=0,l,k[l]);
887         intvector upper_limit(m-1);
888
889         for (size_t l=0; l<m-1; ++l) {
890                 k[l] = 0;
891                 k_cum[l] = 0;
892                 upper_limit[l] = n;
893         }
894
895         while (true) {
896                 exvector term;
897                 term.reserve(m+1);
898                 for (std::size_t l = 0; l < m - 1; ++l) {
899                         const ex & b = a.op(l);
900                         GINAC_ASSERT(!is_exactly_a<add>(b));
901                         GINAC_ASSERT(!is_exactly_a<power>(b) ||
902                                      !is_exactly_a<numeric>(ex_to<power>(b).exponent) ||
903                                      !ex_to<numeric>(ex_to<power>(b).exponent).is_pos_integer() ||
904                                      !is_exactly_a<add>(ex_to<power>(b).basis) ||
905                                      !is_exactly_a<mul>(ex_to<power>(b).basis) ||
906                                      !is_exactly_a<power>(ex_to<power>(b).basis));
907                         if (is_exactly_a<mul>(b))
908                                 term.push_back(expand_mul(ex_to<mul>(b), numeric(k[l]), options, true));
909                         else
910                                 term.push_back(power(b,k[l]));
911                 }
912
913                 const ex & b = a.op(m - 1);
914                 GINAC_ASSERT(!is_exactly_a<add>(b));
915                 GINAC_ASSERT(!is_exactly_a<power>(b) ||
916                              !is_exactly_a<numeric>(ex_to<power>(b).exponent) ||
917                              !ex_to<numeric>(ex_to<power>(b).exponent).is_pos_integer() ||
918                              !is_exactly_a<add>(ex_to<power>(b).basis) ||
919                              !is_exactly_a<mul>(ex_to<power>(b).basis) ||
920                              !is_exactly_a<power>(ex_to<power>(b).basis));
921                 if (is_exactly_a<mul>(b))
922                         term.push_back(expand_mul(ex_to<mul>(b), numeric(n-k_cum[m-2]), options, true));
923                 else
924                         term.push_back(power(b,n-k_cum[m-2]));
925
926                 numeric f = binomial(numeric(n),numeric(k[0]));
927                 for (std::size_t l = 1; l < m - 1; ++l)
928                         f *= binomial(numeric(n-k_cum[l-1]),numeric(k[l]));
929
930                 term.push_back(f);
931
932                 result.push_back(ex((new mul(term))->setflag(status_flags::dynallocated)).expand(options));
933
934                 // increment k[]
935                 bool done = false;
936                 std::size_t l = m - 2;
937                 while ((++k[l]) > upper_limit[l]) {
938                         k[l] = 0;
939                         if (l != 0)
940                                 --l;
941                         else {
942                                 done = true;
943                                 break;
944                         }
945                 }
946                 if (done)
947                         break;
948
949                 // recalc k_cum[] and upper_limit[]
950                 k_cum[l] = (l==0 ? k[0] : k_cum[l-1]+k[l]);
951
952                 for (size_t i=l+1; i<m-1; ++i)
953                         k_cum[i] = k_cum[i-1]+k[i];
954
955                 for (size_t i=l+1; i<m-1; ++i)
956                         upper_limit[i] = n-k_cum[i-1];
957         }
958
959         return (new add(result))->setflag(status_flags::dynallocated |
960                                           status_flags::expanded);
961 }
962
963
964 /** Special case of power::expand_add. Expands a^2 where a is an add.
965  *  @see power::expand_add */
966 ex power::expand_add_2(const add & a, unsigned options) const
967 {
968         epvector sum;
969         size_t a_nops = a.nops();
970         sum.reserve((a_nops*(a_nops+1))/2);
971         epvector::const_iterator last = a.seq.end();
972
973         // power(+(x,...,z;c),2)=power(+(x,...,z;0),2)+2*c*+(x,...,z;0)+c*c
974         // first part: ignore overall_coeff and expand other terms
975         for (epvector::const_iterator cit0=a.seq.begin(); cit0!=last; ++cit0) {
976                 const ex & r = cit0->rest;
977                 const ex & c = cit0->coeff;
978                 
979                 GINAC_ASSERT(!is_exactly_a<add>(r));
980                 GINAC_ASSERT(!is_exactly_a<power>(r) ||
981                              !is_exactly_a<numeric>(ex_to<power>(r).exponent) ||
982                              !ex_to<numeric>(ex_to<power>(r).exponent).is_pos_integer() ||
983                              !is_exactly_a<add>(ex_to<power>(r).basis) ||
984                              !is_exactly_a<mul>(ex_to<power>(r).basis) ||
985                              !is_exactly_a<power>(ex_to<power>(r).basis));
986                 
987                 if (c.is_equal(_ex1)) {
988                         if (is_exactly_a<mul>(r)) {
989                                 sum.push_back(expair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
990                                                      _ex1));
991                         } else {
992                                 sum.push_back(expair((new power(r,_ex2))->setflag(status_flags::dynallocated),
993                                                      _ex1));
994                         }
995                 } else {
996                         if (is_exactly_a<mul>(r)) {
997                                 sum.push_back(a.combine_ex_with_coeff_to_pair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
998                                                      ex_to<numeric>(c).power_dyn(*_num2_p)));
999                         } else {
1000                                 sum.push_back(a.combine_ex_with_coeff_to_pair((new power(r,_ex2))->setflag(status_flags::dynallocated),
1001                                                      ex_to<numeric>(c).power_dyn(*_num2_p)));
1002                         }
1003                 }
1004
1005                 for (epvector::const_iterator cit1=cit0+1; cit1!=last; ++cit1) {
1006                         const ex & r1 = cit1->rest;
1007                         const ex & c1 = cit1->coeff;
1008                         sum.push_back(a.combine_ex_with_coeff_to_pair((new mul(r,r1))->setflag(status_flags::dynallocated),
1009                                                                       _num2_p->mul(ex_to<numeric>(c)).mul_dyn(ex_to<numeric>(c1))));
1010                 }
1011         }
1012         
1013         GINAC_ASSERT(sum.size()==(a.seq.size()*(a.seq.size()+1))/2);
1014         
1015         // second part: add terms coming from overall_factor (if != 0)
1016         if (!a.overall_coeff.is_zero()) {
1017                 epvector::const_iterator i = a.seq.begin(), end = a.seq.end();
1018                 while (i != end) {
1019                         sum.push_back(a.combine_pair_with_coeff_to_pair(*i, ex_to<numeric>(a.overall_coeff).mul_dyn(*_num2_p)));
1020                         ++i;
1021                 }
1022                 sum.push_back(expair(ex_to<numeric>(a.overall_coeff).power_dyn(*_num2_p),_ex1));
1023         }
1024         
1025         GINAC_ASSERT(sum.size()==(a_nops*(a_nops+1))/2);
1026         
1027         return (new add(sum))->setflag(status_flags::dynallocated | status_flags::expanded);
1028 }
1029
1030 /** Expand factors of m in m^n where m is a mul and n is an integer.
1031  *  @see power::expand */
1032 ex power::expand_mul(const mul & m, const numeric & n, unsigned options, bool from_expand) const
1033 {
1034         GINAC_ASSERT(n.is_integer());
1035
1036         if (n.is_zero()) {
1037                 return _ex1;
1038         }
1039
1040         // do not bother to rename indices if there are no any.
1041         if ((!(options & expand_options::expand_rename_idx)) 
1042                         && m.info(info_flags::has_indices))
1043                 options |= expand_options::expand_rename_idx;
1044         // Leave it to multiplication since dummy indices have to be renamed
1045         if ((options & expand_options::expand_rename_idx) &&
1046                 (get_all_dummy_indices(m).size() > 0) && n.is_positive()) {
1047                 ex result = m;
1048                 exvector va = get_all_dummy_indices(m);
1049                 sort(va.begin(), va.end(), ex_is_less());
1050
1051                 for (int i=1; i < n.to_int(); i++)
1052                         result *= rename_dummy_indices_uniquely(va, m);
1053                 return result;
1054         }
1055
1056         epvector distrseq;
1057         distrseq.reserve(m.seq.size());
1058         bool need_reexpand = false;
1059
1060         epvector::const_iterator last = m.seq.end();
1061         epvector::const_iterator cit = m.seq.begin();
1062         while (cit!=last) {
1063                 expair p = m.combine_pair_with_coeff_to_pair(*cit, n);
1064                 if (from_expand && is_exactly_a<add>(cit->rest) && ex_to<numeric>(p.coeff).is_pos_integer()) {
1065                         // this happens when e.g. (a+b)^(1/2) gets squared and
1066                         // the resulting product needs to be reexpanded
1067                         need_reexpand = true;
1068                 }
1069                 distrseq.push_back(p);
1070                 ++cit;
1071         }
1072
1073         const mul & result = static_cast<const mul &>((new mul(distrseq, ex_to<numeric>(m.overall_coeff).power_dyn(n)))->setflag(status_flags::dynallocated));
1074         if (need_reexpand)
1075                 return ex(result).expand(options);
1076         if (from_expand)
1077                 return result.setflag(status_flags::expanded);
1078         return result;
1079 }
1080
1081 GINAC_BIND_UNARCHIVER(power);
1082
1083 } // namespace GiNaC