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