]> www.ginac.de Git - ginac.git/blob - ginac/power.cpp
G_numeric: fix numeric evaluation with trailing zeros and y != 1.
[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 (exponent.has(var))
293                 return false;
294         if (!exponent.info(info_flags::nonnegint))
295                 return false;
296         return basis.is_polynomial(var);
297 }
298
299 int power::degree(const ex & s) const
300 {
301         if (is_equal(ex_to<basic>(s)))
302                 return 1;
303         else if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
304                 if (basis.is_equal(s))
305                         return ex_to<numeric>(exponent).to_int();
306                 else
307                         return basis.degree(s) * ex_to<numeric>(exponent).to_int();
308         } else if (basis.has(s))
309                 throw(std::runtime_error("power::degree(): undefined degree because of non-integer exponent"));
310         else
311                 return 0;
312 }
313
314 int power::ldegree(const ex & s) const 
315 {
316         if (is_equal(ex_to<basic>(s)))
317                 return 1;
318         else if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
319                 if (basis.is_equal(s))
320                         return ex_to<numeric>(exponent).to_int();
321                 else
322                         return basis.ldegree(s) * ex_to<numeric>(exponent).to_int();
323         } else if (basis.has(s))
324                 throw(std::runtime_error("power::ldegree(): undefined degree because of non-integer exponent"));
325         else
326                 return 0;
327 }
328
329 ex power::coeff(const ex & s, int n) const
330 {
331         if (is_equal(ex_to<basic>(s)))
332                 return n==1 ? _ex1 : _ex0;
333         else if (!basis.is_equal(s)) {
334                 // basis not equal to s
335                 if (n == 0)
336                         return *this;
337                 else
338                         return _ex0;
339         } else {
340                 // basis equal to s
341                 if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
342                         // integer exponent
343                         int int_exp = ex_to<numeric>(exponent).to_int();
344                         if (n == int_exp)
345                                 return _ex1;
346                         else
347                                 return _ex0;
348                 } else {
349                         // non-integer exponents are treated as zero
350                         if (n == 0)
351                                 return *this;
352                         else
353                                 return _ex0;
354                 }
355         }
356 }
357
358 /** Perform automatic term rewriting rules in this class.  In the following
359  *  x, x1, x2,... stand for a symbolic variables of type ex and c, c1, c2...
360  *  stand for such expressions that contain a plain number.
361  *  - ^(x,0) -> 1  (also handles ^(0,0))
362  *  - ^(x,1) -> x
363  *  - ^(0,c) -> 0 or exception  (depending on the real part of c)
364  *  - ^(1,x) -> 1
365  *  - ^(c1,c2) -> *(c1^n,c1^(c2-n))  (so that 0<(c2-n)<1, try to evaluate roots, possibly in numerator and denominator of c1)
366  *  - ^(^(x,c1),c2) -> ^(x,c1*c2)  if x is positive and c1 is real.
367  *  - ^(^(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!)
368  *  - ^(*(x,y,z),c) -> *(x^c,y^c,z^c)  (if c integer)
369  *  - ^(*(x,c1),c2) -> ^(x,c2)*c1^c2  (c1>0)
370  *  - ^(*(x,c1),c2) -> ^(-x,c2)*c1^c2  (c1<0)
371  *
372  *  @param level cut-off in recursive evaluation */
373 ex power::eval(int level) const
374 {
375         if ((level==1) && (flags & status_flags::evaluated))
376                 return *this;
377         else if (level == -max_recursion_level)
378                 throw(std::runtime_error("max recursion level reached"));
379         
380         const ex & ebasis    = level==1 ? basis    : basis.eval(level-1);
381         const ex & eexponent = level==1 ? exponent : exponent.eval(level-1);
382         
383         const numeric *num_basis = NULL;
384         const numeric *num_exponent = NULL;
385         
386         if (is_exactly_a<numeric>(ebasis)) {
387                 num_basis = &ex_to<numeric>(ebasis);
388         }
389         if (is_exactly_a<numeric>(eexponent)) {
390                 num_exponent = &ex_to<numeric>(eexponent);
391         }
392         
393         // ^(x,0) -> 1  (0^0 also handled here)
394         if (eexponent.is_zero()) {
395                 if (ebasis.is_zero())
396                         throw (std::domain_error("power::eval(): pow(0,0) is undefined"));
397                 else
398                         return _ex1;
399         }
400         
401         // ^(x,1) -> x
402         if (eexponent.is_equal(_ex1))
403                 return ebasis;
404
405         // ^(0,c1) -> 0 or exception  (depending on real value of c1)
406         if ( ebasis.is_zero() && num_exponent ) {
407                 if ((num_exponent->real()).is_zero())
408                         throw (std::domain_error("power::eval(): pow(0,I) is undefined"));
409                 else if ((num_exponent->real()).is_negative())
410                         throw (pole_error("power::eval(): division by zero",1));
411                 else
412                         return _ex0;
413         }
414
415         // ^(1,x) -> 1
416         if (ebasis.is_equal(_ex1))
417                 return _ex1;
418
419         // power of a function calculated by separate rules defined for this function
420         if (is_exactly_a<function>(ebasis))
421                 return ex_to<function>(ebasis).power(eexponent);
422
423         // Turn (x^c)^d into x^(c*d) in the case that x is positive and c is real.
424         if (is_exactly_a<power>(ebasis) && ebasis.op(0).info(info_flags::positive) && ebasis.op(1).info(info_flags::real))
425                 return power(ebasis.op(0), ebasis.op(1) * eexponent);
426
427         if ( num_exponent ) {
428
429                 // ^(c1,c2) -> c1^c2  (c1, c2 numeric(),
430                 // except if c1,c2 are rational, but c1^c2 is not)
431                 if ( num_basis ) {
432                         const bool basis_is_crational = num_basis->is_crational();
433                         const bool exponent_is_crational = num_exponent->is_crational();
434                         if (!basis_is_crational || !exponent_is_crational) {
435                                 // return a plain float
436                                 return (new numeric(num_basis->power(*num_exponent)))->setflag(status_flags::dynallocated |
437                                                                                                status_flags::evaluated |
438                                                                                                status_flags::expanded);
439                         }
440
441                         const numeric res = num_basis->power(*num_exponent);
442                         if (res.is_crational()) {
443                                 return res;
444                         }
445                         GINAC_ASSERT(!num_exponent->is_integer());  // has been handled by now
446
447                         // ^(c1,n/m) -> *(c1^q,c1^(n/m-q)), 0<(n/m-q)<1, q integer
448                         if (basis_is_crational && exponent_is_crational
449                             && num_exponent->is_real()
450                             && !num_exponent->is_integer()) {
451                                 const numeric n = num_exponent->numer();
452                                 const numeric m = num_exponent->denom();
453                                 numeric r;
454                                 numeric q = iquo(n, m, r);
455                                 if (r.is_negative()) {
456                                         r += m;
457                                         --q;
458                                 }
459                                 if (q.is_zero()) {  // the exponent was in the allowed range 0<(n/m)<1
460                                         if (num_basis->is_rational() && !num_basis->is_integer()) {
461                                                 // try it for numerator and denominator separately, in order to
462                                                 // partially simplify things like (5/8)^(1/3) -> 1/2*5^(1/3)
463                                                 const numeric bnum = num_basis->numer();
464                                                 const numeric bden = num_basis->denom();
465                                                 const numeric res_bnum = bnum.power(*num_exponent);
466                                                 const numeric res_bden = bden.power(*num_exponent);
467                                                 if (res_bnum.is_integer())
468                                                         return (new mul(power(bden,-*num_exponent),res_bnum))->setflag(status_flags::dynallocated | status_flags::evaluated);
469                                                 if (res_bden.is_integer())
470                                                         return (new mul(power(bnum,*num_exponent),res_bden.inverse()))->setflag(status_flags::dynallocated | status_flags::evaluated);
471                                         }
472                                         return this->hold();
473                                 } else {
474                                         // assemble resulting product, but allowing for a re-evaluation,
475                                         // because otherwise we'll end up with something like
476                                         //    (7/8)^(4/3)  ->  7/8*(1/2*7^(1/3))
477                                         // instead of 7/16*7^(1/3).
478                                         ex prod = power(*num_basis,r.div(m));
479                                         return prod*power(*num_basis,q);
480                                 }
481                         }
482                 }
483         
484                 // ^(^(x,c1),c2) -> ^(x,c1*c2)
485                 // (c1, c2 numeric(), c2 integer or -1 < c1 <= 1 or (c1=-1 and c2>0),
486                 // case c1==1 should not happen, see below!)
487                 if (is_exactly_a<power>(ebasis)) {
488                         const power & sub_power = ex_to<power>(ebasis);
489                         const ex & sub_basis = sub_power.basis;
490                         const ex & sub_exponent = sub_power.exponent;
491                         if (is_exactly_a<numeric>(sub_exponent)) {
492                                 const numeric & num_sub_exponent = ex_to<numeric>(sub_exponent);
493                                 GINAC_ASSERT(num_sub_exponent!=numeric(1));
494                                 if (num_exponent->is_integer() || (abs(num_sub_exponent) - (*_num1_p)).is_negative() 
495                                                 || (num_sub_exponent == *_num_1_p && num_exponent->is_positive())) {
496                                         return power(sub_basis,num_sub_exponent.mul(*num_exponent));
497                                 }
498                         }
499                 }
500         
501                 // ^(*(x,y,z),c1) -> *(x^c1,y^c1,z^c1) (c1 integer)
502                 if (num_exponent->is_integer() && is_exactly_a<mul>(ebasis)) {
503                         return expand_mul(ex_to<mul>(ebasis), *num_exponent, 0);
504                 }
505
506                 // (2*x + 6*y)^(-4) -> 1/16*(x + 3*y)^(-4)
507                 if (num_exponent->is_integer() && is_exactly_a<add>(ebasis)) {
508                         numeric icont = ebasis.integer_content();
509                         const numeric lead_coeff = 
510                                 ex_to<numeric>(ex_to<add>(ebasis).seq.begin()->coeff).div(icont);
511
512                         const bool canonicalizable = lead_coeff.is_integer();
513                         const bool unit_normal = lead_coeff.is_pos_integer();
514                         if (canonicalizable && (! unit_normal))
515                                 icont = icont.mul(*_num_1_p);
516                         
517                         if (canonicalizable && (icont != *_num1_p)) {
518                                 const add& addref = ex_to<add>(ebasis);
519                                 add* addp = new add(addref);
520                                 addp->setflag(status_flags::dynallocated);
521                                 addp->clearflag(status_flags::hash_calculated);
522                                 addp->overall_coeff = ex_to<numeric>(addp->overall_coeff).div_dyn(icont);
523                                 for (epvector::iterator i = addp->seq.begin(); i != addp->seq.end(); ++i)
524                                         i->coeff = ex_to<numeric>(i->coeff).div_dyn(icont);
525
526                                 const numeric c = icont.power(*num_exponent);
527                                 if (likely(c != *_num1_p))
528                                         return (new mul(power(*addp, *num_exponent), c))->setflag(status_flags::dynallocated);
529                                 else
530                                         return power(*addp, *num_exponent);
531                         }
532                 }
533
534                 // ^(*(...,x;c1),c2) -> *(^(*(...,x;1),c2),c1^c2)  (c1, c2 numeric(), c1>0)
535                 // ^(*(...,x;c1),c2) -> *(^(*(...,x;-1),c2),(-c1)^c2)  (c1, c2 numeric(), c1<0)
536                 if (is_exactly_a<mul>(ebasis)) {
537                         GINAC_ASSERT(!num_exponent->is_integer()); // should have been handled above
538                         const mul & mulref = ex_to<mul>(ebasis);
539                         if (!mulref.overall_coeff.is_equal(_ex1)) {
540                                 const numeric & num_coeff = ex_to<numeric>(mulref.overall_coeff);
541                                 if (num_coeff.is_real()) {
542                                         if (num_coeff.is_positive()) {
543                                                 mul *mulp = new mul(mulref);
544                                                 mulp->overall_coeff = _ex1;
545                                                 mulp->setflag(status_flags::dynallocated);
546                                                 mulp->clearflag(status_flags::evaluated);
547                                                 mulp->clearflag(status_flags::hash_calculated);
548                                                 return (new mul(power(*mulp,exponent),
549                                                                 power(num_coeff,*num_exponent)))->setflag(status_flags::dynallocated);
550                                         } else {
551                                                 GINAC_ASSERT(num_coeff.compare(*_num0_p)<0);
552                                                 if (!num_coeff.is_equal(*_num_1_p)) {
553                                                         mul *mulp = new mul(mulref);
554                                                         mulp->overall_coeff = _ex_1;
555                                                         mulp->setflag(status_flags::dynallocated);
556                                                         mulp->clearflag(status_flags::evaluated);
557                                                         mulp->clearflag(status_flags::hash_calculated);
558                                                         return (new mul(power(*mulp,exponent),
559                                                                         power(abs(num_coeff),*num_exponent)))->setflag(status_flags::dynallocated);
560                                                 }
561                                         }
562                                 }
563                         }
564                 }
565
566                 // ^(nc,c1) -> ncmul(nc,nc,...) (c1 positive integer, unless nc is a matrix)
567                 if (num_exponent->is_pos_integer() &&
568                     ebasis.return_type() != return_types::commutative &&
569                     !is_a<matrix>(ebasis)) {
570                         return ncmul(exvector(num_exponent->to_int(), ebasis), true);
571                 }
572         }
573         
574         if (are_ex_trivially_equal(ebasis,basis) &&
575             are_ex_trivially_equal(eexponent,exponent)) {
576                 return this->hold();
577         }
578         return (new power(ebasis, eexponent))->setflag(status_flags::dynallocated |
579                                                        status_flags::evaluated);
580 }
581
582 ex power::evalf(int level) const
583 {
584         ex ebasis;
585         ex eexponent;
586         
587         if (level==1) {
588                 ebasis = basis;
589                 eexponent = exponent;
590         } else if (level == -max_recursion_level) {
591                 throw(std::runtime_error("max recursion level reached"));
592         } else {
593                 ebasis = basis.evalf(level-1);
594                 if (!is_exactly_a<numeric>(exponent))
595                         eexponent = exponent.evalf(level-1);
596                 else
597                         eexponent = exponent;
598         }
599
600         return power(ebasis,eexponent);
601 }
602
603 ex power::evalm() const
604 {
605         const ex ebasis = basis.evalm();
606         const ex eexponent = exponent.evalm();
607         if (is_a<matrix>(ebasis)) {
608                 if (is_exactly_a<numeric>(eexponent)) {
609                         return (new matrix(ex_to<matrix>(ebasis).pow(eexponent)))->setflag(status_flags::dynallocated);
610                 }
611         }
612         return (new power(ebasis, eexponent))->setflag(status_flags::dynallocated);
613 }
614
615 bool power::has(const ex & other, unsigned options) const
616 {
617         if (!(options & has_options::algebraic))
618                 return basic::has(other, options);
619         if (!is_a<power>(other))
620                 return basic::has(other, options);
621         if (!exponent.info(info_flags::integer)
622                         || !other.op(1).info(info_flags::integer))
623                 return basic::has(other, options);
624         if (exponent.info(info_flags::posint)
625                         && other.op(1).info(info_flags::posint)
626                         && ex_to<numeric>(exponent).to_int()
627                                         > ex_to<numeric>(other.op(1)).to_int()
628                         && basis.match(other.op(0)))
629                 return true;
630         if (exponent.info(info_flags::negint)
631                         && other.op(1).info(info_flags::negint)
632                         && ex_to<numeric>(exponent).to_int()
633                                         < ex_to<numeric>(other.op(1)).to_int()
634                         && basis.match(other.op(0)))
635                 return true;
636         return basic::has(other, options);
637 }
638
639 // from mul.cpp
640 extern bool tryfactsubs(const ex &, const ex &, int &, exmap&);
641
642 ex power::subs(const exmap & m, unsigned options) const
643 {       
644         const ex &subsed_basis = basis.subs(m, options);
645         const ex &subsed_exponent = exponent.subs(m, options);
646
647         if (!are_ex_trivially_equal(basis, subsed_basis)
648          || !are_ex_trivially_equal(exponent, subsed_exponent)) 
649                 return power(subsed_basis, subsed_exponent).subs_one_level(m, options);
650
651         if (!(options & subs_options::algebraic))
652                 return subs_one_level(m, options);
653
654         for (exmap::const_iterator it = m.begin(); it != m.end(); ++it) {
655                 int nummatches = std::numeric_limits<int>::max();
656                 exmap repls;
657                 if (tryfactsubs(*this, it->first, nummatches, repls)) {
658                         ex anum = it->second.subs(repls, subs_options::no_pattern);
659                         ex aden = it->first.subs(repls, subs_options::no_pattern);
660                         ex result = (*this)*power(anum/aden, nummatches);
661                         return (ex_to<basic>(result)).subs_one_level(m, options);
662                 }
663         }
664
665         return subs_one_level(m, options);
666 }
667
668 ex power::eval_ncmul(const exvector & v) const
669 {
670         return inherited::eval_ncmul(v);
671 }
672
673 ex power::conjugate() const
674 {
675         // conjugate(pow(x,y))==pow(conjugate(x),conjugate(y)) unless on the
676         // branch cut which runs along the negative real axis.
677         if (basis.info(info_flags::positive)) {
678                 ex newexponent = exponent.conjugate();
679                 if (are_ex_trivially_equal(exponent, newexponent)) {
680                         return *this;
681                 }
682                 return (new power(basis, newexponent))->setflag(status_flags::dynallocated);
683         }
684         if (exponent.info(info_flags::integer)) {
685                 ex newbasis = basis.conjugate();
686                 if (are_ex_trivially_equal(basis, newbasis)) {
687                         return *this;
688                 }
689                 return (new power(newbasis, exponent))->setflag(status_flags::dynallocated);
690         }
691         return conjugate_function(*this).hold();
692 }
693
694 ex power::real_part() const
695 {
696         if (exponent.info(info_flags::integer)) {
697                 ex basis_real = basis.real_part();
698                 if (basis_real == basis)
699                         return *this;
700                 realsymbol a("a"),b("b");
701                 ex result;
702                 if (exponent.info(info_flags::posint))
703                         result = power(a+I*b,exponent);
704                 else
705                         result = power(a/(a*a+b*b)-I*b/(a*a+b*b),-exponent);
706                 result = result.expand();
707                 result = result.real_part();
708                 result = result.subs(lst( a==basis_real, b==basis.imag_part() ));
709                 return result;
710         }
711         
712         ex a = basis.real_part();
713         ex b = basis.imag_part();
714         ex c = exponent.real_part();
715         ex d = exponent.imag_part();
716         return power(abs(basis),c)*exp(-d*atan2(b,a))*cos(c*atan2(b,a)+d*log(abs(basis)));
717 }
718
719 ex power::imag_part() const
720 {
721         if (exponent.info(info_flags::integer)) {
722                 ex basis_real = basis.real_part();
723                 if (basis_real == basis)
724                         return 0;
725                 realsymbol a("a"),b("b");
726                 ex result;
727                 if (exponent.info(info_flags::posint))
728                         result = power(a+I*b,exponent);
729                 else
730                         result = power(a/(a*a+b*b)-I*b/(a*a+b*b),-exponent);
731                 result = result.expand();
732                 result = result.imag_part();
733                 result = result.subs(lst( a==basis_real, b==basis.imag_part() ));
734                 return result;
735         }
736         
737         ex a=basis.real_part();
738         ex b=basis.imag_part();
739         ex c=exponent.real_part();
740         ex d=exponent.imag_part();
741         return power(abs(basis),c)*exp(-d*atan2(b,a))*sin(c*atan2(b,a)+d*log(abs(basis)));
742 }
743
744 // protected
745
746 // protected
747
748 /** Implementation of ex::diff() for a power.
749  *  @see ex::diff */
750 ex power::derivative(const symbol & s) const
751 {
752         if (is_a<numeric>(exponent)) {
753                 // D(b^r) = r * b^(r-1) * D(b) (faster than the formula below)
754                 epvector newseq;
755                 newseq.reserve(2);
756                 newseq.push_back(expair(basis, exponent - _ex1));
757                 newseq.push_back(expair(basis.diff(s), _ex1));
758                 return mul(newseq, exponent);
759         } else {
760                 // D(b^e) = b^e * (D(e)*ln(b) + e*D(b)/b)
761                 return mul(*this,
762                            add(mul(exponent.diff(s), log(basis)),
763                            mul(mul(exponent, basis.diff(s)), power(basis, _ex_1))));
764         }
765 }
766
767 int power::compare_same_type(const basic & other) const
768 {
769         GINAC_ASSERT(is_exactly_a<power>(other));
770         const power &o = static_cast<const power &>(other);
771
772         int cmpval = basis.compare(o.basis);
773         if (cmpval)
774                 return cmpval;
775         else
776                 return exponent.compare(o.exponent);
777 }
778
779 unsigned power::return_type() const
780 {
781         return basis.return_type();
782 }
783
784 return_type_t power::return_type_tinfo() const
785 {
786         return basis.return_type_tinfo();
787 }
788
789 ex power::expand(unsigned options) const
790 {
791         if (is_a<symbol>(basis) && exponent.info(info_flags::integer)) {
792                 // A special case worth optimizing.
793                 setflag(status_flags::expanded);
794                 return *this;
795         }
796
797         const ex expanded_basis = basis.expand(options);
798         const ex expanded_exponent = exponent.expand(options);
799         
800         // x^(a+b) -> x^a * x^b
801         if (is_exactly_a<add>(expanded_exponent)) {
802                 const add &a = ex_to<add>(expanded_exponent);
803                 exvector distrseq;
804                 distrseq.reserve(a.seq.size() + 1);
805                 epvector::const_iterator last = a.seq.end();
806                 epvector::const_iterator cit = a.seq.begin();
807                 while (cit!=last) {
808                         distrseq.push_back(power(expanded_basis, a.recombine_pair_to_ex(*cit)));
809                         ++cit;
810                 }
811                 
812                 // Make sure that e.g. (x+y)^(2+a) expands the (x+y)^2 factor
813                 if (ex_to<numeric>(a.overall_coeff).is_integer()) {
814                         const numeric &num_exponent = ex_to<numeric>(a.overall_coeff);
815                         int int_exponent = num_exponent.to_int();
816                         if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
817                                 distrseq.push_back(expand_add(ex_to<add>(expanded_basis), int_exponent, options));
818                         else
819                                 distrseq.push_back(power(expanded_basis, a.overall_coeff));
820                 } else
821                         distrseq.push_back(power(expanded_basis, a.overall_coeff));
822                 
823                 // Make sure that e.g. (x+y)^(1+a) -> x*(x+y)^a + y*(x+y)^a
824                 ex r = (new mul(distrseq))->setflag(status_flags::dynallocated);
825                 return r.expand(options);
826         }
827         
828         if (!is_exactly_a<numeric>(expanded_exponent) ||
829                 !ex_to<numeric>(expanded_exponent).is_integer()) {
830                 if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent)) {
831                         return this->hold();
832                 } else {
833                         return (new power(expanded_basis,expanded_exponent))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
834                 }
835         }
836         
837         // integer numeric exponent
838         const numeric & num_exponent = ex_to<numeric>(expanded_exponent);
839         int int_exponent = num_exponent.to_int();
840         
841         // (x+y)^n, n>0
842         if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
843                 return expand_add(ex_to<add>(expanded_basis), int_exponent, options);
844         
845         // (x*y)^n -> x^n * y^n
846         if (is_exactly_a<mul>(expanded_basis))
847                 return expand_mul(ex_to<mul>(expanded_basis), num_exponent, options, true);
848         
849         // cannot expand further
850         if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent))
851                 return this->hold();
852         else
853                 return (new power(expanded_basis,expanded_exponent))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
854 }
855
856 //////////
857 // new virtual functions which can be overridden by derived classes
858 //////////
859
860 // none
861
862 //////////
863 // non-virtual functions in this class
864 //////////
865
866 /** expand a^n where a is an add and n is a positive integer.
867  *  @see power::expand */
868 ex power::expand_add(const add & a, int n, unsigned options) const
869 {
870         if (n==2)
871                 return expand_add_2(a, options);
872
873         const size_t m = a.nops();
874         exvector result;
875         // The number of terms will be the number of combinatorial compositions,
876         // i.e. the number of unordered arrangements of m nonnegative integers
877         // which sum up to n.  It is frequently written as C_n(m) and directly
878         // related with binomial coefficients:
879         result.reserve(binomial(numeric(n+m-1), numeric(m-1)).to_int());
880         intvector k(m-1);
881         intvector k_cum(m-1); // k_cum[l]:=sum(i=0,l,k[l]);
882         intvector upper_limit(m-1);
883
884         for (size_t l=0; l<m-1; ++l) {
885                 k[l] = 0;
886                 k_cum[l] = 0;
887                 upper_limit[l] = n;
888         }
889
890         while (true) {
891                 exvector term;
892                 term.reserve(m+1);
893                 for (std::size_t l = 0; l < m - 1; ++l) {
894                         const ex & b = a.op(l);
895                         GINAC_ASSERT(!is_exactly_a<add>(b));
896                         GINAC_ASSERT(!is_exactly_a<power>(b) ||
897                                      !is_exactly_a<numeric>(ex_to<power>(b).exponent) ||
898                                      !ex_to<numeric>(ex_to<power>(b).exponent).is_pos_integer() ||
899                                      !is_exactly_a<add>(ex_to<power>(b).basis) ||
900                                      !is_exactly_a<mul>(ex_to<power>(b).basis) ||
901                                      !is_exactly_a<power>(ex_to<power>(b).basis));
902                         if (is_exactly_a<mul>(b))
903                                 term.push_back(expand_mul(ex_to<mul>(b), numeric(k[l]), options, true));
904                         else
905                                 term.push_back(power(b,k[l]));
906                 }
907
908                 const ex & b = a.op(m - 1);
909                 GINAC_ASSERT(!is_exactly_a<add>(b));
910                 GINAC_ASSERT(!is_exactly_a<power>(b) ||
911                              !is_exactly_a<numeric>(ex_to<power>(b).exponent) ||
912                              !ex_to<numeric>(ex_to<power>(b).exponent).is_pos_integer() ||
913                              !is_exactly_a<add>(ex_to<power>(b).basis) ||
914                              !is_exactly_a<mul>(ex_to<power>(b).basis) ||
915                              !is_exactly_a<power>(ex_to<power>(b).basis));
916                 if (is_exactly_a<mul>(b))
917                         term.push_back(expand_mul(ex_to<mul>(b), numeric(n-k_cum[m-2]), options, true));
918                 else
919                         term.push_back(power(b,n-k_cum[m-2]));
920
921                 numeric f = binomial(numeric(n),numeric(k[0]));
922                 for (std::size_t l = 1; l < m - 1; ++l)
923                         f *= binomial(numeric(n-k_cum[l-1]),numeric(k[l]));
924
925                 term.push_back(f);
926
927                 result.push_back(ex((new mul(term))->setflag(status_flags::dynallocated)).expand(options));
928
929                 // increment k[]
930                 bool done = false;
931                 std::size_t l = m - 2;
932                 while ((++k[l]) > upper_limit[l]) {
933                         k[l] = 0;
934                         if (l != 0)
935                                 --l;
936                         else {
937                                 done = true;
938                                 break;
939                         }
940                 }
941                 if (done)
942                         break;
943
944                 // recalc k_cum[] and upper_limit[]
945                 k_cum[l] = (l==0 ? k[0] : k_cum[l-1]+k[l]);
946
947                 for (size_t i=l+1; i<m-1; ++i)
948                         k_cum[i] = k_cum[i-1]+k[i];
949
950                 for (size_t i=l+1; i<m-1; ++i)
951                         upper_limit[i] = n-k_cum[i-1];
952         }
953
954         return (new add(result))->setflag(status_flags::dynallocated |
955                                           status_flags::expanded);
956 }
957
958
959 /** Special case of power::expand_add. Expands a^2 where a is an add.
960  *  @see power::expand_add */
961 ex power::expand_add_2(const add & a, unsigned options) const
962 {
963         epvector sum;
964         size_t a_nops = a.nops();
965         sum.reserve((a_nops*(a_nops+1))/2);
966         epvector::const_iterator last = a.seq.end();
967
968         // power(+(x,...,z;c),2)=power(+(x,...,z;0),2)+2*c*+(x,...,z;0)+c*c
969         // first part: ignore overall_coeff and expand other terms
970         for (epvector::const_iterator cit0=a.seq.begin(); cit0!=last; ++cit0) {
971                 const ex & r = cit0->rest;
972                 const ex & c = cit0->coeff;
973                 
974                 GINAC_ASSERT(!is_exactly_a<add>(r));
975                 GINAC_ASSERT(!is_exactly_a<power>(r) ||
976                              !is_exactly_a<numeric>(ex_to<power>(r).exponent) ||
977                              !ex_to<numeric>(ex_to<power>(r).exponent).is_pos_integer() ||
978                              !is_exactly_a<add>(ex_to<power>(r).basis) ||
979                              !is_exactly_a<mul>(ex_to<power>(r).basis) ||
980                              !is_exactly_a<power>(ex_to<power>(r).basis));
981                 
982                 if (c.is_equal(_ex1)) {
983                         if (is_exactly_a<mul>(r)) {
984                                 sum.push_back(expair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
985                                                      _ex1));
986                         } else {
987                                 sum.push_back(expair((new power(r,_ex2))->setflag(status_flags::dynallocated),
988                                                      _ex1));
989                         }
990                 } else {
991                         if (is_exactly_a<mul>(r)) {
992                                 sum.push_back(a.combine_ex_with_coeff_to_pair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
993                                                      ex_to<numeric>(c).power_dyn(*_num2_p)));
994                         } else {
995                                 sum.push_back(a.combine_ex_with_coeff_to_pair((new power(r,_ex2))->setflag(status_flags::dynallocated),
996                                                      ex_to<numeric>(c).power_dyn(*_num2_p)));
997                         }
998                 }
999
1000                 for (epvector::const_iterator cit1=cit0+1; cit1!=last; ++cit1) {
1001                         const ex & r1 = cit1->rest;
1002                         const ex & c1 = cit1->coeff;
1003                         sum.push_back(a.combine_ex_with_coeff_to_pair((new mul(r,r1))->setflag(status_flags::dynallocated),
1004                                                                       _num2_p->mul(ex_to<numeric>(c)).mul_dyn(ex_to<numeric>(c1))));
1005                 }
1006         }
1007         
1008         GINAC_ASSERT(sum.size()==(a.seq.size()*(a.seq.size()+1))/2);
1009         
1010         // second part: add terms coming from overall_factor (if != 0)
1011         if (!a.overall_coeff.is_zero()) {
1012                 epvector::const_iterator i = a.seq.begin(), end = a.seq.end();
1013                 while (i != end) {
1014                         sum.push_back(a.combine_pair_with_coeff_to_pair(*i, ex_to<numeric>(a.overall_coeff).mul_dyn(*_num2_p)));
1015                         ++i;
1016                 }
1017                 sum.push_back(expair(ex_to<numeric>(a.overall_coeff).power_dyn(*_num2_p),_ex1));
1018         }
1019         
1020         GINAC_ASSERT(sum.size()==(a_nops*(a_nops+1))/2);
1021         
1022         return (new add(sum))->setflag(status_flags::dynallocated | status_flags::expanded);
1023 }
1024
1025 /** Expand factors of m in m^n where m is a mul and n is an integer.
1026  *  @see power::expand */
1027 ex power::expand_mul(const mul & m, const numeric & n, unsigned options, bool from_expand) const
1028 {
1029         GINAC_ASSERT(n.is_integer());
1030
1031         if (n.is_zero()) {
1032                 return _ex1;
1033         }
1034
1035         // do not bother to rename indices if there are no any.
1036         if ((!(options & expand_options::expand_rename_idx)) 
1037                         && m.info(info_flags::has_indices))
1038                 options |= expand_options::expand_rename_idx;
1039         // Leave it to multiplication since dummy indices have to be renamed
1040         if ((options & expand_options::expand_rename_idx) &&
1041                 (get_all_dummy_indices(m).size() > 0) && n.is_positive()) {
1042                 ex result = m;
1043                 exvector va = get_all_dummy_indices(m);
1044                 sort(va.begin(), va.end(), ex_is_less());
1045
1046                 for (int i=1; i < n.to_int(); i++)
1047                         result *= rename_dummy_indices_uniquely(va, m);
1048                 return result;
1049         }
1050
1051         epvector distrseq;
1052         distrseq.reserve(m.seq.size());
1053         bool need_reexpand = false;
1054
1055         epvector::const_iterator last = m.seq.end();
1056         epvector::const_iterator cit = m.seq.begin();
1057         while (cit!=last) {
1058                 expair p = m.combine_pair_with_coeff_to_pair(*cit, n);
1059                 if (from_expand && is_exactly_a<add>(cit->rest) && ex_to<numeric>(p.coeff).is_pos_integer()) {
1060                         // this happens when e.g. (a+b)^(1/2) gets squared and
1061                         // the resulting product needs to be reexpanded
1062                         need_reexpand = true;
1063                 }
1064                 distrseq.push_back(p);
1065                 ++cit;
1066         }
1067
1068         const mul & result = static_cast<const mul &>((new mul(distrseq, ex_to<numeric>(m.overall_coeff).power_dyn(n)))->setflag(status_flags::dynallocated));
1069         if (need_reexpand)
1070                 return ex(result).expand(options);
1071         if (from_expand)
1072                 return result.setflag(status_flags::expanded);
1073         return result;
1074 }
1075
1076 GINAC_BIND_UNARCHIVER(power);
1077
1078 } // namespace GiNaC