3 * Implementation of GiNaC's symbolic exponentiation (basis^exponent). */
6 * GiNaC Copyright (C) 1999-2007 Johannes Gutenberg University Mainz, Germany
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.
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.
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
29 #include "expairseq.h"
35 #include "operators.h"
36 #include "inifcns.h" // for log() in power::derivative()
43 #include "relational.h"
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))
56 typedef std::vector<int> intvector;
59 // default constructor
62 power::power() : inherited(&power::tinfo_static) { }
74 power::power(const archive_node &n, lst &sym_lst) : inherited(n, sym_lst)
76 n.find_ex("basis", basis, sym_lst);
77 n.find_ex("exponent", exponent, sym_lst);
80 void power::archive(archive_node &n) const
82 inherited::archive(n);
83 n.add_ex("basis", basis);
84 n.add_ex("exponent", exponent);
87 DEFAULT_UNARCHIVE(power)
90 // functions overriding virtual functions from base classes
95 void power::print_power(const print_context & c, const char *powersymbol, const char *openbrace, const char *closebrace, unsigned level) const
97 // Ordinary output of powers using '^' or '**'
98 if (precedence() <= level)
99 c.s << openbrace << '(';
100 basis.print(c, precedence());
103 exponent.print(c, precedence());
105 if (precedence() <= level)
106 c.s << ')' << closebrace;
109 void power::do_print_dflt(const print_dflt & c, unsigned level) const
111 if (exponent.is_equal(_ex1_2)) {
113 // Square roots are printed in a special way
119 print_power(c, "^", "", "", level);
122 void power::do_print_latex(const print_latex & c, unsigned level) const
124 if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_negative()) {
126 // Powers with negative numeric exponents are printed as fractions
128 power(basis, -exponent).eval().print(c);
131 } else if (exponent.is_equal(_ex1_2)) {
133 // Square roots are printed in a special way
139 print_power(c, "^", "{", "}", level);
142 static void print_sym_pow(const print_context & c, const symbol &x, int exp)
144 // Optimal output of integer powers of symbols to aid compiler CSE.
145 // C.f. ISO/IEC 14882:1998, section 1.9 [intro execution], paragraph 15
146 // to learn why such a parenthesation is really necessary.
149 } else if (exp == 2) {
153 } else if (exp & 1) {
156 print_sym_pow(c, x, exp-1);
159 print_sym_pow(c, x, exp >> 1);
161 print_sym_pow(c, x, exp >> 1);
166 void power::do_print_csrc_cl_N(const print_csrc_cl_N& c, unsigned level) const
168 if (exponent.is_equal(_ex_1)) {
181 void power::do_print_csrc(const print_csrc & c, unsigned level) const
183 // Integer powers of symbols are printed in a special, optimized way
184 if (exponent.info(info_flags::integer)
185 && (is_a<symbol>(basis) || is_a<constant>(basis))) {
186 int exp = ex_to<numeric>(exponent).to_int();
193 print_sym_pow(c, ex_to<symbol>(basis), exp);
196 // <expr>^-1 is printed as "1.0/<expr>" or with the recip() function of CLN
197 } else if (exponent.is_equal(_ex_1)) {
202 // Otherwise, use the pow() function
212 void power::do_print_python(const print_python & c, unsigned level) const
214 print_power(c, "**", "", "", level);
217 void power::do_print_python_repr(const print_python_repr & c, unsigned level) const
219 c.s << class_name() << '(';
226 bool power::info(unsigned inf) const
229 case info_flags::polynomial:
230 case info_flags::integer_polynomial:
231 case info_flags::cinteger_polynomial:
232 case info_flags::rational_polynomial:
233 case info_flags::crational_polynomial:
234 return exponent.info(info_flags::nonnegint) &&
236 case info_flags::rational_function:
237 return exponent.info(info_flags::integer) &&
239 case info_flags::algebraic:
240 return !exponent.info(info_flags::integer) ||
242 case info_flags::expanded:
243 return (flags & status_flags::expanded);
245 return inherited::info(inf);
248 size_t power::nops() const
253 ex power::op(size_t i) const
257 return i==0 ? basis : exponent;
260 ex power::map(map_function & f) const
262 const ex &mapped_basis = f(basis);
263 const ex &mapped_exponent = f(exponent);
265 if (!are_ex_trivially_equal(basis, mapped_basis)
266 || !are_ex_trivially_equal(exponent, mapped_exponent))
267 return (new power(mapped_basis, mapped_exponent))->setflag(status_flags::dynallocated);
272 bool power::is_polynomial(const ex & var) const
274 if (exponent.has(var))
276 if (!exponent.info(info_flags::nonnegint))
278 return basis.is_polynomial(var);
281 int power::degree(const ex & s) const
283 if (is_equal(ex_to<basic>(s)))
285 else if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
286 if (basis.is_equal(s))
287 return ex_to<numeric>(exponent).to_int();
289 return basis.degree(s) * ex_to<numeric>(exponent).to_int();
290 } else if (basis.has(s))
291 throw(std::runtime_error("power::degree(): undefined degree because of non-integer exponent"));
296 int power::ldegree(const ex & s) const
298 if (is_equal(ex_to<basic>(s)))
300 else if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
301 if (basis.is_equal(s))
302 return ex_to<numeric>(exponent).to_int();
304 return basis.ldegree(s) * ex_to<numeric>(exponent).to_int();
305 } else if (basis.has(s))
306 throw(std::runtime_error("power::ldegree(): undefined degree because of non-integer exponent"));
311 ex power::coeff(const ex & s, int n) const
313 if (is_equal(ex_to<basic>(s)))
314 return n==1 ? _ex1 : _ex0;
315 else if (!basis.is_equal(s)) {
316 // basis not equal to s
323 if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
325 int int_exp = ex_to<numeric>(exponent).to_int();
331 // non-integer exponents are treated as zero
340 /** Perform automatic term rewriting rules in this class. In the following
341 * x, x1, x2,... stand for a symbolic variables of type ex and c, c1, c2...
342 * stand for such expressions that contain a plain number.
343 * - ^(x,0) -> 1 (also handles ^(0,0))
345 * - ^(0,c) -> 0 or exception (depending on the real part of c)
347 * - ^(c1,c2) -> *(c1^n,c1^(c2-n)) (so that 0<(c2-n)<1, try to evaluate roots, possibly in numerator and denominator of c1)
348 * - ^(^(x,c1),c2) -> ^(x,c1*c2) if x is positive and c1 is real.
349 * - ^(^(x,c1),c2) -> ^(x,c1*c2) (c2 integer or -1 < c1 <= 1, case c1=1 should not happen, see below!)
350 * - ^(*(x,y,z),c) -> *(x^c,y^c,z^c) (if c integer)
351 * - ^(*(x,c1),c2) -> ^(x,c2)*c1^c2 (c1>0)
352 * - ^(*(x,c1),c2) -> ^(-x,c2)*c1^c2 (c1<0)
354 * @param level cut-off in recursive evaluation */
355 ex power::eval(int level) const
357 if ((level==1) && (flags & status_flags::evaluated))
359 else if (level == -max_recursion_level)
360 throw(std::runtime_error("max recursion level reached"));
362 const ex & ebasis = level==1 ? basis : basis.eval(level-1);
363 const ex & eexponent = level==1 ? exponent : exponent.eval(level-1);
365 bool basis_is_numerical = false;
366 bool exponent_is_numerical = false;
367 const numeric *num_basis;
368 const numeric *num_exponent;
370 if (is_exactly_a<numeric>(ebasis)) {
371 basis_is_numerical = true;
372 num_basis = &ex_to<numeric>(ebasis);
374 if (is_exactly_a<numeric>(eexponent)) {
375 exponent_is_numerical = true;
376 num_exponent = &ex_to<numeric>(eexponent);
379 // ^(x,0) -> 1 (0^0 also handled here)
380 if (eexponent.is_zero()) {
381 if (ebasis.is_zero())
382 throw (std::domain_error("power::eval(): pow(0,0) is undefined"));
388 if (eexponent.is_equal(_ex1))
391 // ^(0,c1) -> 0 or exception (depending on real value of c1)
392 if (ebasis.is_zero() && exponent_is_numerical) {
393 if ((num_exponent->real()).is_zero())
394 throw (std::domain_error("power::eval(): pow(0,I) is undefined"));
395 else if ((num_exponent->real()).is_negative())
396 throw (pole_error("power::eval(): division by zero",1));
402 if (ebasis.is_equal(_ex1))
405 // power of a function calculated by separate rules defined for this function
406 if (is_exactly_a<function>(ebasis))
407 return ex_to<function>(ebasis).power(eexponent);
409 // Turn (x^c)^d into x^(c*d) in the case that x is positive and c is real.
410 if (is_exactly_a<power>(ebasis) && ebasis.op(0).info(info_flags::positive) && ebasis.op(1).info(info_flags::real))
411 return power(ebasis.op(0), ebasis.op(1) * eexponent);
413 if (exponent_is_numerical) {
415 // ^(c1,c2) -> c1^c2 (c1, c2 numeric(),
416 // except if c1,c2 are rational, but c1^c2 is not)
417 if (basis_is_numerical) {
418 const bool basis_is_crational = num_basis->is_crational();
419 const bool exponent_is_crational = num_exponent->is_crational();
420 if (!basis_is_crational || !exponent_is_crational) {
421 // return a plain float
422 return (new numeric(num_basis->power(*num_exponent)))->setflag(status_flags::dynallocated |
423 status_flags::evaluated |
424 status_flags::expanded);
427 const numeric res = num_basis->power(*num_exponent);
428 if (res.is_crational()) {
431 GINAC_ASSERT(!num_exponent->is_integer()); // has been handled by now
433 // ^(c1,n/m) -> *(c1^q,c1^(n/m-q)), 0<(n/m-q)<1, q integer
434 if (basis_is_crational && exponent_is_crational
435 && num_exponent->is_real()
436 && !num_exponent->is_integer()) {
437 const numeric n = num_exponent->numer();
438 const numeric m = num_exponent->denom();
440 numeric q = iquo(n, m, r);
441 if (r.is_negative()) {
445 if (q.is_zero()) { // the exponent was in the allowed range 0<(n/m)<1
446 if (num_basis->is_rational() && !num_basis->is_integer()) {
447 // try it for numerator and denominator separately, in order to
448 // partially simplify things like (5/8)^(1/3) -> 1/2*5^(1/3)
449 const numeric bnum = num_basis->numer();
450 const numeric bden = num_basis->denom();
451 const numeric res_bnum = bnum.power(*num_exponent);
452 const numeric res_bden = bden.power(*num_exponent);
453 if (res_bnum.is_integer())
454 return (new mul(power(bden,-*num_exponent),res_bnum))->setflag(status_flags::dynallocated | status_flags::evaluated);
455 if (res_bden.is_integer())
456 return (new mul(power(bnum,*num_exponent),res_bden.inverse()))->setflag(status_flags::dynallocated | status_flags::evaluated);
460 // assemble resulting product, but allowing for a re-evaluation,
461 // because otherwise we'll end up with something like
462 // (7/8)^(4/3) -> 7/8*(1/2*7^(1/3))
463 // instead of 7/16*7^(1/3).
464 ex prod = power(*num_basis,r.div(m));
465 return prod*power(*num_basis,q);
470 // ^(^(x,c1),c2) -> ^(x,c1*c2)
471 // (c1, c2 numeric(), c2 integer or -1 < c1 <= 1,
472 // case c1==1 should not happen, see below!)
473 if (is_exactly_a<power>(ebasis)) {
474 const power & sub_power = ex_to<power>(ebasis);
475 const ex & sub_basis = sub_power.basis;
476 const ex & sub_exponent = sub_power.exponent;
477 if (is_exactly_a<numeric>(sub_exponent)) {
478 const numeric & num_sub_exponent = ex_to<numeric>(sub_exponent);
479 GINAC_ASSERT(num_sub_exponent!=numeric(1));
480 if (num_exponent->is_integer() || (abs(num_sub_exponent) - (*_num1_p)).is_negative()) {
481 return power(sub_basis,num_sub_exponent.mul(*num_exponent));
486 // ^(*(x,y,z),c1) -> *(x^c1,y^c1,z^c1) (c1 integer)
487 if (num_exponent->is_integer() && is_exactly_a<mul>(ebasis)) {
488 return expand_mul(ex_to<mul>(ebasis), *num_exponent, 0);
491 // (2*x + 6*y)^(-4) -> 1/16*(x + 3*y)^(-4)
492 if (num_exponent->is_integer() && is_exactly_a<add>(ebasis)) {
493 numeric icont = ebasis.integer_content();
494 const numeric& lead_coeff =
495 ex_to<numeric>(ex_to<add>(ebasis).seq.begin()->coeff).div_dyn(icont);
497 const bool canonicalizable = lead_coeff.is_integer();
498 const bool unit_normal = lead_coeff.is_pos_integer();
499 if (canonicalizable && (! unit_normal))
500 icont = icont.mul(*_num_1_p);
502 if (canonicalizable && (icont != *_num1_p)) {
503 const add& addref = ex_to<add>(ebasis);
504 add* addp = new add(addref);
505 addp->setflag(status_flags::dynallocated);
506 addp->clearflag(status_flags::hash_calculated);
507 addp->overall_coeff = ex_to<numeric>(addp->overall_coeff).div_dyn(icont);
508 for (epvector::iterator i = addp->seq.begin(); i != addp->seq.end(); ++i)
509 i->coeff = ex_to<numeric>(i->coeff).div_dyn(icont);
511 const numeric c = icont.power(*num_exponent);
512 if (likely(c != *_num1_p))
513 return (new mul(power(*addp, *num_exponent), c))->setflag(status_flags::dynallocated);
515 return power(*addp, *num_exponent);
519 // ^(*(...,x;c1),c2) -> *(^(*(...,x;1),c2),c1^c2) (c1, c2 numeric(), c1>0)
520 // ^(*(...,x;c1),c2) -> *(^(*(...,x;-1),c2),(-c1)^c2) (c1, c2 numeric(), c1<0)
521 if (is_exactly_a<mul>(ebasis)) {
522 GINAC_ASSERT(!num_exponent->is_integer()); // should have been handled above
523 const mul & mulref = ex_to<mul>(ebasis);
524 if (!mulref.overall_coeff.is_equal(_ex1)) {
525 const numeric & num_coeff = ex_to<numeric>(mulref.overall_coeff);
526 if (num_coeff.is_real()) {
527 if (num_coeff.is_positive()) {
528 mul *mulp = new mul(mulref);
529 mulp->overall_coeff = _ex1;
530 mulp->clearflag(status_flags::evaluated);
531 mulp->clearflag(status_flags::hash_calculated);
532 return (new mul(power(*mulp,exponent),
533 power(num_coeff,*num_exponent)))->setflag(status_flags::dynallocated);
535 GINAC_ASSERT(num_coeff.compare(*_num0_p)<0);
536 if (!num_coeff.is_equal(*_num_1_p)) {
537 mul *mulp = new mul(mulref);
538 mulp->overall_coeff = _ex_1;
539 mulp->clearflag(status_flags::evaluated);
540 mulp->clearflag(status_flags::hash_calculated);
541 return (new mul(power(*mulp,exponent),
542 power(abs(num_coeff),*num_exponent)))->setflag(status_flags::dynallocated);
549 // ^(nc,c1) -> ncmul(nc,nc,...) (c1 positive integer, unless nc is a matrix)
550 if (num_exponent->is_pos_integer() &&
551 ebasis.return_type() != return_types::commutative &&
552 !is_a<matrix>(ebasis)) {
553 return ncmul(exvector(num_exponent->to_int(), ebasis), true);
557 if (are_ex_trivially_equal(ebasis,basis) &&
558 are_ex_trivially_equal(eexponent,exponent)) {
561 return (new power(ebasis, eexponent))->setflag(status_flags::dynallocated |
562 status_flags::evaluated);
565 ex power::evalf(int level) const
572 eexponent = exponent;
573 } else if (level == -max_recursion_level) {
574 throw(std::runtime_error("max recursion level reached"));
576 ebasis = basis.evalf(level-1);
577 if (!is_exactly_a<numeric>(exponent))
578 eexponent = exponent.evalf(level-1);
580 eexponent = exponent;
583 return power(ebasis,eexponent);
586 ex power::evalm() const
588 const ex ebasis = basis.evalm();
589 const ex eexponent = exponent.evalm();
590 if (is_a<matrix>(ebasis)) {
591 if (is_exactly_a<numeric>(eexponent)) {
592 return (new matrix(ex_to<matrix>(ebasis).pow(eexponent)))->setflag(status_flags::dynallocated);
595 return (new power(ebasis, eexponent))->setflag(status_flags::dynallocated);
598 bool power::has(const ex & other, unsigned options) const
600 if (!(options & has_options::algebraic))
601 return basic::has(other, options);
602 if (!is_a<power>(other))
603 return basic::has(other, options);
604 if (!exponent.info(info_flags::integer)
605 || !other.op(1).info(info_flags::integer))
606 return basic::has(other, options);
607 if (exponent.info(info_flags::posint)
608 && other.op(1).info(info_flags::posint)
609 && ex_to<numeric>(exponent).to_int()
610 > ex_to<numeric>(other.op(1)).to_int()
611 && basis.match(other.op(0)))
613 if (exponent.info(info_flags::negint)
614 && other.op(1).info(info_flags::negint)
615 && ex_to<numeric>(exponent).to_int()
616 < ex_to<numeric>(other.op(1)).to_int()
617 && basis.match(other.op(0)))
619 return basic::has(other, options);
623 extern bool tryfactsubs(const ex &, const ex &, int &, lst &);
625 ex power::subs(const exmap & m, unsigned options) const
627 const ex &subsed_basis = basis.subs(m, options);
628 const ex &subsed_exponent = exponent.subs(m, options);
630 if (!are_ex_trivially_equal(basis, subsed_basis)
631 || !are_ex_trivially_equal(exponent, subsed_exponent))
632 return power(subsed_basis, subsed_exponent).subs_one_level(m, options);
634 if (!(options & subs_options::algebraic))
635 return subs_one_level(m, options);
637 for (exmap::const_iterator it = m.begin(); it != m.end(); ++it) {
638 int nummatches = std::numeric_limits<int>::max();
640 if (tryfactsubs(*this, it->first, nummatches, repls))
641 return (ex_to<basic>((*this) * power(it->second.subs(ex(repls), subs_options::no_pattern) / it->first.subs(ex(repls), subs_options::no_pattern), nummatches))).subs_one_level(m, options);
644 return subs_one_level(m, options);
647 ex power::eval_ncmul(const exvector & v) const
649 return inherited::eval_ncmul(v);
652 ex power::conjugate() const
654 ex newbasis = basis.conjugate();
655 ex newexponent = exponent.conjugate();
656 if (are_ex_trivially_equal(basis, newbasis) && are_ex_trivially_equal(exponent, newexponent)) {
659 return (new power(newbasis, newexponent))->setflag(status_flags::dynallocated);
662 ex power::real_part() const
664 if (exponent.info(info_flags::integer)) {
665 ex basis_real = basis.real_part();
666 if (basis_real == basis)
668 realsymbol a("a"),b("b");
670 if (exponent.info(info_flags::posint))
671 result = power(a+I*b,exponent);
673 result = power(a/(a*a+b*b)-I*b/(a*a+b*b),-exponent);
674 result = result.expand();
675 result = result.real_part();
676 result = result.subs(lst( a==basis_real, b==basis.imag_part() ));
680 ex a = basis.real_part();
681 ex b = basis.imag_part();
682 ex c = exponent.real_part();
683 ex d = exponent.imag_part();
684 return power(abs(basis),c)*exp(-d*atan2(b,a))*cos(c*atan2(b,a)+d*log(abs(basis)));
687 ex power::imag_part() const
689 if (exponent.info(info_flags::integer)) {
690 ex basis_real = basis.real_part();
691 if (basis_real == basis)
693 realsymbol a("a"),b("b");
695 if (exponent.info(info_flags::posint))
696 result = power(a+I*b,exponent);
698 result = power(a/(a*a+b*b)-I*b/(a*a+b*b),-exponent);
699 result = result.expand();
700 result = result.imag_part();
701 result = result.subs(lst( a==basis_real, b==basis.imag_part() ));
705 ex a=basis.real_part();
706 ex b=basis.imag_part();
707 ex c=exponent.real_part();
708 ex d=exponent.imag_part();
710 power(abs(basis),c)*exp(-d*atan2(b,a))*sin(c*atan2(b,a)+d*log(abs(basis)));
717 /** Implementation of ex::diff() for a power.
719 ex power::derivative(const symbol & s) const
721 if (is_a<numeric>(exponent)) {
722 // D(b^r) = r * b^(r-1) * D(b) (faster than the formula below)
725 newseq.push_back(expair(basis, exponent - _ex1));
726 newseq.push_back(expair(basis.diff(s), _ex1));
727 return mul(newseq, exponent);
729 // D(b^e) = b^e * (D(e)*ln(b) + e*D(b)/b)
731 add(mul(exponent.diff(s), log(basis)),
732 mul(mul(exponent, basis.diff(s)), power(basis, _ex_1))));
736 int power::compare_same_type(const basic & other) const
738 GINAC_ASSERT(is_exactly_a<power>(other));
739 const power &o = static_cast<const power &>(other);
741 int cmpval = basis.compare(o.basis);
745 return exponent.compare(o.exponent);
748 unsigned power::return_type() const
750 return basis.return_type();
753 tinfo_t power::return_type_tinfo() const
755 return basis.return_type_tinfo();
758 ex power::expand(unsigned options) const
760 if (options == 0 && (flags & status_flags::expanded))
763 const ex expanded_basis = basis.expand(options);
764 const ex expanded_exponent = exponent.expand(options);
766 // x^(a+b) -> x^a * x^b
767 if (is_exactly_a<add>(expanded_exponent)) {
768 const add &a = ex_to<add>(expanded_exponent);
770 distrseq.reserve(a.seq.size() + 1);
771 epvector::const_iterator last = a.seq.end();
772 epvector::const_iterator cit = a.seq.begin();
774 distrseq.push_back(power(expanded_basis, a.recombine_pair_to_ex(*cit)));
778 // Make sure that e.g. (x+y)^(2+a) expands the (x+y)^2 factor
779 if (ex_to<numeric>(a.overall_coeff).is_integer()) {
780 const numeric &num_exponent = ex_to<numeric>(a.overall_coeff);
781 int int_exponent = num_exponent.to_int();
782 if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
783 distrseq.push_back(expand_add(ex_to<add>(expanded_basis), int_exponent, options));
785 distrseq.push_back(power(expanded_basis, a.overall_coeff));
787 distrseq.push_back(power(expanded_basis, a.overall_coeff));
789 // Make sure that e.g. (x+y)^(1+a) -> x*(x+y)^a + y*(x+y)^a
790 ex r = (new mul(distrseq))->setflag(status_flags::dynallocated);
791 return r.expand(options);
794 if (!is_exactly_a<numeric>(expanded_exponent) ||
795 !ex_to<numeric>(expanded_exponent).is_integer()) {
796 if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent)) {
799 return (new power(expanded_basis,expanded_exponent))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
803 // integer numeric exponent
804 const numeric & num_exponent = ex_to<numeric>(expanded_exponent);
805 int int_exponent = num_exponent.to_int();
808 if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
809 return expand_add(ex_to<add>(expanded_basis), int_exponent, options);
811 // (x*y)^n -> x^n * y^n
812 if (is_exactly_a<mul>(expanded_basis))
813 return expand_mul(ex_to<mul>(expanded_basis), num_exponent, options, true);
815 // cannot expand further
816 if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent))
819 return (new power(expanded_basis,expanded_exponent))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
823 // new virtual functions which can be overridden by derived classes
829 // non-virtual functions in this class
832 /** expand a^n where a is an add and n is a positive integer.
833 * @see power::expand */
834 ex power::expand_add(const add & a, int n, unsigned options) const
837 return expand_add_2(a, options);
839 const size_t m = a.nops();
841 // The number of terms will be the number of combinatorial compositions,
842 // i.e. the number of unordered arrangements of m nonnegative integers
843 // which sum up to n. It is frequently written as C_n(m) and directly
844 // related with binomial coefficients:
845 result.reserve(binomial(numeric(n+m-1), numeric(m-1)).to_int());
847 intvector k_cum(m-1); // k_cum[l]:=sum(i=0,l,k[l]);
848 intvector upper_limit(m-1);
851 for (size_t l=0; l<m-1; ++l) {
860 for (l=0; l<m-1; ++l) {
861 const ex & b = a.op(l);
862 GINAC_ASSERT(!is_exactly_a<add>(b));
863 GINAC_ASSERT(!is_exactly_a<power>(b) ||
864 !is_exactly_a<numeric>(ex_to<power>(b).exponent) ||
865 !ex_to<numeric>(ex_to<power>(b).exponent).is_pos_integer() ||
866 !is_exactly_a<add>(ex_to<power>(b).basis) ||
867 !is_exactly_a<mul>(ex_to<power>(b).basis) ||
868 !is_exactly_a<power>(ex_to<power>(b).basis));
869 if (is_exactly_a<mul>(b))
870 term.push_back(expand_mul(ex_to<mul>(b), numeric(k[l]), options, true));
872 term.push_back(power(b,k[l]));
875 const ex & b = a.op(l);
876 GINAC_ASSERT(!is_exactly_a<add>(b));
877 GINAC_ASSERT(!is_exactly_a<power>(b) ||
878 !is_exactly_a<numeric>(ex_to<power>(b).exponent) ||
879 !ex_to<numeric>(ex_to<power>(b).exponent).is_pos_integer() ||
880 !is_exactly_a<add>(ex_to<power>(b).basis) ||
881 !is_exactly_a<mul>(ex_to<power>(b).basis) ||
882 !is_exactly_a<power>(ex_to<power>(b).basis));
883 if (is_exactly_a<mul>(b))
884 term.push_back(expand_mul(ex_to<mul>(b), numeric(n-k_cum[m-2]), options, true));
886 term.push_back(power(b,n-k_cum[m-2]));
888 numeric f = binomial(numeric(n),numeric(k[0]));
889 for (l=1; l<m-1; ++l)
890 f *= binomial(numeric(n-k_cum[l-1]),numeric(k[l]));
894 result.push_back(ex((new mul(term))->setflag(status_flags::dynallocated)).expand(options));
898 while ((l>=0) && ((++k[l])>upper_limit[l])) {
904 // recalc k_cum[] and upper_limit[]
905 k_cum[l] = (l==0 ? k[0] : k_cum[l-1]+k[l]);
907 for (size_t i=l+1; i<m-1; ++i)
908 k_cum[i] = k_cum[i-1]+k[i];
910 for (size_t i=l+1; i<m-1; ++i)
911 upper_limit[i] = n-k_cum[i-1];
914 return (new add(result))->setflag(status_flags::dynallocated |
915 status_flags::expanded);
919 /** Special case of power::expand_add. Expands a^2 where a is an add.
920 * @see power::expand_add */
921 ex power::expand_add_2(const add & a, unsigned options) const
924 size_t a_nops = a.nops();
925 sum.reserve((a_nops*(a_nops+1))/2);
926 epvector::const_iterator last = a.seq.end();
928 // power(+(x,...,z;c),2)=power(+(x,...,z;0),2)+2*c*+(x,...,z;0)+c*c
929 // first part: ignore overall_coeff and expand other terms
930 for (epvector::const_iterator cit0=a.seq.begin(); cit0!=last; ++cit0) {
931 const ex & r = cit0->rest;
932 const ex & c = cit0->coeff;
934 GINAC_ASSERT(!is_exactly_a<add>(r));
935 GINAC_ASSERT(!is_exactly_a<power>(r) ||
936 !is_exactly_a<numeric>(ex_to<power>(r).exponent) ||
937 !ex_to<numeric>(ex_to<power>(r).exponent).is_pos_integer() ||
938 !is_exactly_a<add>(ex_to<power>(r).basis) ||
939 !is_exactly_a<mul>(ex_to<power>(r).basis) ||
940 !is_exactly_a<power>(ex_to<power>(r).basis));
942 if (c.is_equal(_ex1)) {
943 if (is_exactly_a<mul>(r)) {
944 sum.push_back(expair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
947 sum.push_back(expair((new power(r,_ex2))->setflag(status_flags::dynallocated),
951 if (is_exactly_a<mul>(r)) {
952 sum.push_back(a.combine_ex_with_coeff_to_pair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
953 ex_to<numeric>(c).power_dyn(*_num2_p)));
955 sum.push_back(a.combine_ex_with_coeff_to_pair((new power(r,_ex2))->setflag(status_flags::dynallocated),
956 ex_to<numeric>(c).power_dyn(*_num2_p)));
960 for (epvector::const_iterator cit1=cit0+1; cit1!=last; ++cit1) {
961 const ex & r1 = cit1->rest;
962 const ex & c1 = cit1->coeff;
963 sum.push_back(a.combine_ex_with_coeff_to_pair((new mul(r,r1))->setflag(status_flags::dynallocated),
964 _num2_p->mul(ex_to<numeric>(c)).mul_dyn(ex_to<numeric>(c1))));
968 GINAC_ASSERT(sum.size()==(a.seq.size()*(a.seq.size()+1))/2);
970 // second part: add terms coming from overall_factor (if != 0)
971 if (!a.overall_coeff.is_zero()) {
972 epvector::const_iterator i = a.seq.begin(), end = a.seq.end();
974 sum.push_back(a.combine_pair_with_coeff_to_pair(*i, ex_to<numeric>(a.overall_coeff).mul_dyn(*_num2_p)));
977 sum.push_back(expair(ex_to<numeric>(a.overall_coeff).power_dyn(*_num2_p),_ex1));
980 GINAC_ASSERT(sum.size()==(a_nops*(a_nops+1))/2);
982 return (new add(sum))->setflag(status_flags::dynallocated | status_flags::expanded);
985 /** Expand factors of m in m^n where m is a mul and n is an integer.
986 * @see power::expand */
987 ex power::expand_mul(const mul & m, const numeric & n, unsigned options, bool from_expand) const
989 GINAC_ASSERT(n.is_integer());
995 // Leave it to multiplication since dummy indices have to be renamed
996 if (get_all_dummy_indices(m).size() > 0 && n.is_positive()) {
998 exvector va = get_all_dummy_indices(m);
999 sort(va.begin(), va.end(), ex_is_less());
1001 for (int i=1; i < n.to_int(); i++)
1002 result *= rename_dummy_indices_uniquely(va, m);
1007 distrseq.reserve(m.seq.size());
1008 bool need_reexpand = false;
1010 epvector::const_iterator last = m.seq.end();
1011 epvector::const_iterator cit = m.seq.begin();
1013 expair p = m.combine_pair_with_coeff_to_pair(*cit, n);
1014 if (from_expand && is_exactly_a<add>(cit->rest) && ex_to<numeric>(p.coeff).is_pos_integer()) {
1015 // this happens when e.g. (a+b)^(1/2) gets squared and
1016 // the resulting product needs to be reexpanded
1017 need_reexpand = true;
1019 distrseq.push_back(p);
1023 const mul & result = static_cast<const mul &>((new mul(distrseq, ex_to<numeric>(m.overall_coeff).power_dyn(n)))->setflag(status_flags::dynallocated));
1025 return ex(result).expand(options);
1027 return result.setflag(status_flags::expanded);
1031 } // namespace GiNaC