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))
55 typedef std::vector<int> intvector;
58 // default constructor
61 power::power() : inherited(&power::tinfo_static) { }
73 power::power(const archive_node &n, lst &sym_lst) : inherited(n, sym_lst)
75 n.find_ex("basis", basis, sym_lst);
76 n.find_ex("exponent", exponent, sym_lst);
79 void power::archive(archive_node &n) const
81 inherited::archive(n);
82 n.add_ex("basis", basis);
83 n.add_ex("exponent", exponent);
86 DEFAULT_UNARCHIVE(power)
89 // functions overriding virtual functions from base classes
94 void power::print_power(const print_context & c, const char *powersymbol, const char *openbrace, const char *closebrace, unsigned level) const
96 // Ordinary output of powers using '^' or '**'
97 if (precedence() <= level)
98 c.s << openbrace << '(';
99 basis.print(c, precedence());
102 exponent.print(c, precedence());
104 if (precedence() <= level)
105 c.s << ')' << closebrace;
108 void power::do_print_dflt(const print_dflt & c, unsigned level) const
110 if (exponent.is_equal(_ex1_2)) {
112 // Square roots are printed in a special way
118 print_power(c, "^", "", "", level);
121 void power::do_print_latex(const print_latex & c, unsigned level) const
123 if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_negative()) {
125 // Powers with negative numeric exponents are printed as fractions
127 power(basis, -exponent).eval().print(c);
130 } else if (exponent.is_equal(_ex1_2)) {
132 // Square roots are printed in a special way
138 print_power(c, "^", "{", "}", level);
141 static void print_sym_pow(const print_context & c, const symbol &x, int exp)
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.
148 } else if (exp == 2) {
152 } else if (exp & 1) {
155 print_sym_pow(c, x, exp-1);
158 print_sym_pow(c, x, exp >> 1);
160 print_sym_pow(c, x, exp >> 1);
165 void power::do_print_csrc(const print_csrc & c, unsigned level) const
167 // Integer powers of symbols are printed in a special, optimized way
168 if (exponent.info(info_flags::integer)
169 && (is_a<symbol>(basis) || is_a<constant>(basis))) {
170 int exp = ex_to<numeric>(exponent).to_int();
175 if (is_a<print_csrc_cl_N>(c))
180 print_sym_pow(c, ex_to<symbol>(basis), exp);
183 // <expr>^-1 is printed as "1.0/<expr>" or with the recip() function of CLN
184 } else if (exponent.is_equal(_ex_1)) {
185 if (is_a<print_csrc_cl_N>(c))
192 // Otherwise, use the pow() or expt() (CLN) functions
194 if (is_a<print_csrc_cl_N>(c))
205 void power::do_print_python(const print_python & c, unsigned level) const
207 print_power(c, "**", "", "", level);
210 void power::do_print_python_repr(const print_python_repr & c, unsigned level) const
212 c.s << class_name() << '(';
219 bool power::info(unsigned inf) const
222 case info_flags::polynomial:
223 case info_flags::integer_polynomial:
224 case info_flags::cinteger_polynomial:
225 case info_flags::rational_polynomial:
226 case info_flags::crational_polynomial:
227 return exponent.info(info_flags::nonnegint) &&
229 case info_flags::rational_function:
230 return exponent.info(info_flags::integer) &&
232 case info_flags::algebraic:
233 return !exponent.info(info_flags::integer) ||
235 case info_flags::expanded:
236 return (flags & status_flags::expanded);
238 return inherited::info(inf);
241 size_t power::nops() const
246 ex power::op(size_t i) const
250 return i==0 ? basis : exponent;
253 ex power::map(map_function & f) const
255 const ex &mapped_basis = f(basis);
256 const ex &mapped_exponent = f(exponent);
258 if (!are_ex_trivially_equal(basis, mapped_basis)
259 || !are_ex_trivially_equal(exponent, mapped_exponent))
260 return (new power(mapped_basis, mapped_exponent))->setflag(status_flags::dynallocated);
265 bool power::is_polynomial(const ex & var) const
267 if (exponent.has(var))
269 if (!exponent.info(info_flags::nonnegint))
271 return basis.is_polynomial(var);
274 int power::degree(const ex & s) const
276 if (is_equal(ex_to<basic>(s)))
278 else if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
279 if (basis.is_equal(s))
280 return ex_to<numeric>(exponent).to_int();
282 return basis.degree(s) * ex_to<numeric>(exponent).to_int();
283 } else if (basis.has(s))
284 throw(std::runtime_error("power::degree(): undefined degree because of non-integer exponent"));
289 int power::ldegree(const ex & s) const
291 if (is_equal(ex_to<basic>(s)))
293 else if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
294 if (basis.is_equal(s))
295 return ex_to<numeric>(exponent).to_int();
297 return basis.ldegree(s) * ex_to<numeric>(exponent).to_int();
298 } else if (basis.has(s))
299 throw(std::runtime_error("power::ldegree(): undefined degree because of non-integer exponent"));
304 ex power::coeff(const ex & s, int n) const
306 if (is_equal(ex_to<basic>(s)))
307 return n==1 ? _ex1 : _ex0;
308 else if (!basis.is_equal(s)) {
309 // basis not equal to s
316 if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
318 int int_exp = ex_to<numeric>(exponent).to_int();
324 // non-integer exponents are treated as zero
333 /** Perform automatic term rewriting rules in this class. In the following
334 * x, x1, x2,... stand for a symbolic variables of type ex and c, c1, c2...
335 * stand for such expressions that contain a plain number.
336 * - ^(x,0) -> 1 (also handles ^(0,0))
338 * - ^(0,c) -> 0 or exception (depending on the real part of c)
340 * - ^(c1,c2) -> *(c1^n,c1^(c2-n)) (so that 0<(c2-n)<1, try to evaluate roots, possibly in numerator and denominator of c1)
341 * - ^(^(x,c1),c2) -> ^(x,c1*c2) if x is positive and c1 is real.
342 * - ^(^(x,c1),c2) -> ^(x,c1*c2) (c2 integer or -1 < c1 <= 1, case c1=1 should not happen, see below!)
343 * - ^(*(x,y,z),c) -> *(x^c,y^c,z^c) (if c integer)
344 * - ^(*(x,c1),c2) -> ^(x,c2)*c1^c2 (c1>0)
345 * - ^(*(x,c1),c2) -> ^(-x,c2)*c1^c2 (c1<0)
347 * @param level cut-off in recursive evaluation */
348 ex power::eval(int level) const
350 if ((level==1) && (flags & status_flags::evaluated))
352 else if (level == -max_recursion_level)
353 throw(std::runtime_error("max recursion level reached"));
355 const ex & ebasis = level==1 ? basis : basis.eval(level-1);
356 const ex & eexponent = level==1 ? exponent : exponent.eval(level-1);
358 bool basis_is_numerical = false;
359 bool exponent_is_numerical = false;
360 const numeric *num_basis;
361 const numeric *num_exponent;
363 if (is_exactly_a<numeric>(ebasis)) {
364 basis_is_numerical = true;
365 num_basis = &ex_to<numeric>(ebasis);
367 if (is_exactly_a<numeric>(eexponent)) {
368 exponent_is_numerical = true;
369 num_exponent = &ex_to<numeric>(eexponent);
372 // ^(x,0) -> 1 (0^0 also handled here)
373 if (eexponent.is_zero()) {
374 if (ebasis.is_zero())
375 throw (std::domain_error("power::eval(): pow(0,0) is undefined"));
381 if (eexponent.is_equal(_ex1))
384 // ^(0,c1) -> 0 or exception (depending on real value of c1)
385 if (ebasis.is_zero() && exponent_is_numerical) {
386 if ((num_exponent->real()).is_zero())
387 throw (std::domain_error("power::eval(): pow(0,I) is undefined"));
388 else if ((num_exponent->real()).is_negative())
389 throw (pole_error("power::eval(): division by zero",1));
395 if (ebasis.is_equal(_ex1))
398 // power of a function calculated by separate rules defined for this function
399 if (is_exactly_a<function>(ebasis))
400 return ex_to<function>(ebasis).power(eexponent);
402 // Turn (x^c)^d into x^(c*d) in the case that x is positive and c is real.
403 if (is_exactly_a<power>(ebasis) && ebasis.op(0).info(info_flags::positive) && ebasis.op(1).info(info_flags::real))
404 return power(ebasis.op(0), ebasis.op(1) * eexponent);
406 if (exponent_is_numerical) {
408 // ^(c1,c2) -> c1^c2 (c1, c2 numeric(),
409 // except if c1,c2 are rational, but c1^c2 is not)
410 if (basis_is_numerical) {
411 const bool basis_is_crational = num_basis->is_crational();
412 const bool exponent_is_crational = num_exponent->is_crational();
413 if (!basis_is_crational || !exponent_is_crational) {
414 // return a plain float
415 return (new numeric(num_basis->power(*num_exponent)))->setflag(status_flags::dynallocated |
416 status_flags::evaluated |
417 status_flags::expanded);
420 const numeric res = num_basis->power(*num_exponent);
421 if (res.is_crational()) {
424 GINAC_ASSERT(!num_exponent->is_integer()); // has been handled by now
426 // ^(c1,n/m) -> *(c1^q,c1^(n/m-q)), 0<(n/m-q)<1, q integer
427 if (basis_is_crational && exponent_is_crational
428 && num_exponent->is_real()
429 && !num_exponent->is_integer()) {
430 const numeric n = num_exponent->numer();
431 const numeric m = num_exponent->denom();
433 numeric q = iquo(n, m, r);
434 if (r.is_negative()) {
438 if (q.is_zero()) { // the exponent was in the allowed range 0<(n/m)<1
439 if (num_basis->is_rational() && !num_basis->is_integer()) {
440 // try it for numerator and denominator separately, in order to
441 // partially simplify things like (5/8)^(1/3) -> 1/2*5^(1/3)
442 const numeric bnum = num_basis->numer();
443 const numeric bden = num_basis->denom();
444 const numeric res_bnum = bnum.power(*num_exponent);
445 const numeric res_bden = bden.power(*num_exponent);
446 if (res_bnum.is_integer())
447 return (new mul(power(bden,-*num_exponent),res_bnum))->setflag(status_flags::dynallocated | status_flags::evaluated);
448 if (res_bden.is_integer())
449 return (new mul(power(bnum,*num_exponent),res_bden.inverse()))->setflag(status_flags::dynallocated | status_flags::evaluated);
453 // assemble resulting product, but allowing for a re-evaluation,
454 // because otherwise we'll end up with something like
455 // (7/8)^(4/3) -> 7/8*(1/2*7^(1/3))
456 // instead of 7/16*7^(1/3).
457 ex prod = power(*num_basis,r.div(m));
458 return prod*power(*num_basis,q);
463 // ^(^(x,c1),c2) -> ^(x,c1*c2)
464 // (c1, c2 numeric(), c2 integer or -1 < c1 <= 1,
465 // case c1==1 should not happen, see below!)
466 if (is_exactly_a<power>(ebasis)) {
467 const power & sub_power = ex_to<power>(ebasis);
468 const ex & sub_basis = sub_power.basis;
469 const ex & sub_exponent = sub_power.exponent;
470 if (is_exactly_a<numeric>(sub_exponent)) {
471 const numeric & num_sub_exponent = ex_to<numeric>(sub_exponent);
472 GINAC_ASSERT(num_sub_exponent!=numeric(1));
473 if (num_exponent->is_integer() || (abs(num_sub_exponent) - (*_num1_p)).is_negative()) {
474 return power(sub_basis,num_sub_exponent.mul(*num_exponent));
479 // ^(*(x,y,z),c1) -> *(x^c1,y^c1,z^c1) (c1 integer)
480 if (num_exponent->is_integer() && is_exactly_a<mul>(ebasis)) {
481 return expand_mul(ex_to<mul>(ebasis), *num_exponent, 0);
484 // (2*x + 6*y)^(-4) -> 1/16*(x + 3*y)^(-4)
485 if (num_exponent->is_integer() && is_exactly_a<add>(ebasis)) {
486 numeric icont = ebasis.integer_content();
487 const numeric& lead_coeff =
488 ex_to<numeric>(ex_to<add>(ebasis).seq.begin()->coeff).div_dyn(icont);
490 const bool canonicalizable = lead_coeff.is_integer();
491 const bool unit_normal = lead_coeff.is_pos_integer();
492 if (canonicalizable && (! unit_normal))
493 icont = icont.mul(*_num_1_p);
495 if (canonicalizable && (icont != *_num1_p)) {
496 const add& addref = ex_to<add>(ebasis);
497 add* addp = new add(addref);
498 addp->setflag(status_flags::dynallocated);
499 addp->clearflag(status_flags::hash_calculated);
500 addp->overall_coeff = ex_to<numeric>(addp->overall_coeff).div_dyn(icont);
501 for (epvector::iterator i = addp->seq.begin(); i != addp->seq.end(); ++i)
502 i->coeff = ex_to<numeric>(i->coeff).div_dyn(icont);
504 const numeric c = icont.power(*num_exponent);
505 if (likely(c != *_num1_p))
506 return (new mul(power(*addp, *num_exponent), c))->setflag(status_flags::dynallocated);
508 return power(*addp, *num_exponent);
512 // ^(*(...,x;c1),c2) -> *(^(*(...,x;1),c2),c1^c2) (c1, c2 numeric(), c1>0)
513 // ^(*(...,x;c1),c2) -> *(^(*(...,x;-1),c2),(-c1)^c2) (c1, c2 numeric(), c1<0)
514 if (is_exactly_a<mul>(ebasis)) {
515 GINAC_ASSERT(!num_exponent->is_integer()); // should have been handled above
516 const mul & mulref = ex_to<mul>(ebasis);
517 if (!mulref.overall_coeff.is_equal(_ex1)) {
518 const numeric & num_coeff = ex_to<numeric>(mulref.overall_coeff);
519 if (num_coeff.is_real()) {
520 if (num_coeff.is_positive()) {
521 mul *mulp = new mul(mulref);
522 mulp->overall_coeff = _ex1;
523 mulp->clearflag(status_flags::evaluated);
524 mulp->clearflag(status_flags::hash_calculated);
525 return (new mul(power(*mulp,exponent),
526 power(num_coeff,*num_exponent)))->setflag(status_flags::dynallocated);
528 GINAC_ASSERT(num_coeff.compare(*_num0_p)<0);
529 if (!num_coeff.is_equal(*_num_1_p)) {
530 mul *mulp = new mul(mulref);
531 mulp->overall_coeff = _ex_1;
532 mulp->clearflag(status_flags::evaluated);
533 mulp->clearflag(status_flags::hash_calculated);
534 return (new mul(power(*mulp,exponent),
535 power(abs(num_coeff),*num_exponent)))->setflag(status_flags::dynallocated);
542 // ^(nc,c1) -> ncmul(nc,nc,...) (c1 positive integer, unless nc is a matrix)
543 if (num_exponent->is_pos_integer() &&
544 ebasis.return_type() != return_types::commutative &&
545 !is_a<matrix>(ebasis)) {
546 return ncmul(exvector(num_exponent->to_int(), ebasis), true);
550 if (are_ex_trivially_equal(ebasis,basis) &&
551 are_ex_trivially_equal(eexponent,exponent)) {
554 return (new power(ebasis, eexponent))->setflag(status_flags::dynallocated |
555 status_flags::evaluated);
558 ex power::evalf(int level) const
565 eexponent = exponent;
566 } else if (level == -max_recursion_level) {
567 throw(std::runtime_error("max recursion level reached"));
569 ebasis = basis.evalf(level-1);
570 if (!is_exactly_a<numeric>(exponent))
571 eexponent = exponent.evalf(level-1);
573 eexponent = exponent;
576 return power(ebasis,eexponent);
579 ex power::evalm() const
581 const ex ebasis = basis.evalm();
582 const ex eexponent = exponent.evalm();
583 if (is_a<matrix>(ebasis)) {
584 if (is_exactly_a<numeric>(eexponent)) {
585 return (new matrix(ex_to<matrix>(ebasis).pow(eexponent)))->setflag(status_flags::dynallocated);
588 return (new power(ebasis, eexponent))->setflag(status_flags::dynallocated);
591 bool power::has(const ex & other, unsigned options) const
593 if (!(options & has_options::algebraic))
594 return basic::has(other, options);
595 if (!is_a<power>(other))
596 return basic::has(other, options);
597 if (!exponent.info(info_flags::integer)
598 || !other.op(1).info(info_flags::integer))
599 return basic::has(other, options);
600 if (exponent.info(info_flags::posint)
601 && other.op(1).info(info_flags::posint)
602 && ex_to<numeric>(exponent).to_int()
603 > ex_to<numeric>(other.op(1)).to_int()
604 && basis.match(other.op(0)))
606 if (exponent.info(info_flags::negint)
607 && other.op(1).info(info_flags::negint)
608 && ex_to<numeric>(exponent).to_int()
609 < ex_to<numeric>(other.op(1)).to_int()
610 && basis.match(other.op(0)))
612 return basic::has(other, options);
616 extern bool tryfactsubs(const ex &, const ex &, int &, lst &);
618 ex power::subs(const exmap & m, unsigned options) const
620 const ex &subsed_basis = basis.subs(m, options);
621 const ex &subsed_exponent = exponent.subs(m, options);
623 if (!are_ex_trivially_equal(basis, subsed_basis)
624 || !are_ex_trivially_equal(exponent, subsed_exponent))
625 return power(subsed_basis, subsed_exponent).subs_one_level(m, options);
627 if (!(options & subs_options::algebraic))
628 return subs_one_level(m, options);
630 for (exmap::const_iterator it = m.begin(); it != m.end(); ++it) {
631 int nummatches = std::numeric_limits<int>::max();
633 if (tryfactsubs(*this, it->first, nummatches, repls))
634 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);
637 return subs_one_level(m, options);
640 ex power::eval_ncmul(const exvector & v) const
642 return inherited::eval_ncmul(v);
645 ex power::conjugate() const
647 ex newbasis = basis.conjugate();
648 ex newexponent = exponent.conjugate();
649 if (are_ex_trivially_equal(basis, newbasis) && are_ex_trivially_equal(exponent, newexponent)) {
652 return (new power(newbasis, newexponent))->setflag(status_flags::dynallocated);
655 ex power::real_part() const
657 if (exponent.info(info_flags::integer)) {
658 ex basis_real = basis.real_part();
659 if (basis_real == basis)
661 realsymbol a("a"),b("b");
663 if (exponent.info(info_flags::posint))
664 result = power(a+I*b,exponent);
666 result = power(a/(a*a+b*b)-I*b/(a*a+b*b),-exponent);
667 result = result.expand();
668 result = result.real_part();
669 result = result.subs(lst( a==basis_real, b==basis.imag_part() ));
673 ex a = basis.real_part();
674 ex b = basis.imag_part();
675 ex c = exponent.real_part();
676 ex d = exponent.imag_part();
677 return power(abs(basis),c)*exp(-d*atan2(b,a))*cos(c*atan2(b,a)+d*log(abs(basis)));
680 ex power::imag_part() const
682 if (exponent.info(info_flags::integer)) {
683 ex basis_real = basis.real_part();
684 if (basis_real == basis)
686 realsymbol a("a"),b("b");
688 if (exponent.info(info_flags::posint))
689 result = power(a+I*b,exponent);
691 result = power(a/(a*a+b*b)-I*b/(a*a+b*b),-exponent);
692 result = result.expand();
693 result = result.imag_part();
694 result = result.subs(lst( a==basis_real, b==basis.imag_part() ));
698 ex a=basis.real_part();
699 ex b=basis.imag_part();
700 ex c=exponent.real_part();
701 ex d=exponent.imag_part();
703 power(abs(basis),c)*exp(-d*atan2(b,a))*sin(c*atan2(b,a)+d*log(abs(basis)));
710 /** Implementation of ex::diff() for a power.
712 ex power::derivative(const symbol & s) const
714 if (is_a<numeric>(exponent)) {
715 // D(b^r) = r * b^(r-1) * D(b) (faster than the formula below)
718 newseq.push_back(expair(basis, exponent - _ex1));
719 newseq.push_back(expair(basis.diff(s), _ex1));
720 return mul(newseq, exponent);
722 // D(b^e) = b^e * (D(e)*ln(b) + e*D(b)/b)
724 add(mul(exponent.diff(s), log(basis)),
725 mul(mul(exponent, basis.diff(s)), power(basis, _ex_1))));
729 int power::compare_same_type(const basic & other) const
731 GINAC_ASSERT(is_exactly_a<power>(other));
732 const power &o = static_cast<const power &>(other);
734 int cmpval = basis.compare(o.basis);
738 return exponent.compare(o.exponent);
741 unsigned power::return_type() const
743 return basis.return_type();
746 tinfo_t power::return_type_tinfo() const
748 return basis.return_type_tinfo();
751 ex power::expand(unsigned options) const
753 if (options == 0 && (flags & status_flags::expanded))
756 const ex expanded_basis = basis.expand(options);
757 const ex expanded_exponent = exponent.expand(options);
759 // x^(a+b) -> x^a * x^b
760 if (is_exactly_a<add>(expanded_exponent)) {
761 const add &a = ex_to<add>(expanded_exponent);
763 distrseq.reserve(a.seq.size() + 1);
764 epvector::const_iterator last = a.seq.end();
765 epvector::const_iterator cit = a.seq.begin();
767 distrseq.push_back(power(expanded_basis, a.recombine_pair_to_ex(*cit)));
771 // Make sure that e.g. (x+y)^(2+a) expands the (x+y)^2 factor
772 if (ex_to<numeric>(a.overall_coeff).is_integer()) {
773 const numeric &num_exponent = ex_to<numeric>(a.overall_coeff);
774 int int_exponent = num_exponent.to_int();
775 if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
776 distrseq.push_back(expand_add(ex_to<add>(expanded_basis), int_exponent, options));
778 distrseq.push_back(power(expanded_basis, a.overall_coeff));
780 distrseq.push_back(power(expanded_basis, a.overall_coeff));
782 // Make sure that e.g. (x+y)^(1+a) -> x*(x+y)^a + y*(x+y)^a
783 ex r = (new mul(distrseq))->setflag(status_flags::dynallocated);
784 return r.expand(options);
787 if (!is_exactly_a<numeric>(expanded_exponent) ||
788 !ex_to<numeric>(expanded_exponent).is_integer()) {
789 if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent)) {
792 return (new power(expanded_basis,expanded_exponent))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
796 // integer numeric exponent
797 const numeric & num_exponent = ex_to<numeric>(expanded_exponent);
798 int int_exponent = num_exponent.to_int();
801 if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
802 return expand_add(ex_to<add>(expanded_basis), int_exponent, options);
804 // (x*y)^n -> x^n * y^n
805 if (is_exactly_a<mul>(expanded_basis))
806 return expand_mul(ex_to<mul>(expanded_basis), num_exponent, options, true);
808 // cannot expand further
809 if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent))
812 return (new power(expanded_basis,expanded_exponent))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
816 // new virtual functions which can be overridden by derived classes
822 // non-virtual functions in this class
825 /** expand a^n where a is an add and n is a positive integer.
826 * @see power::expand */
827 ex power::expand_add(const add & a, int n, unsigned options) const
830 return expand_add_2(a, options);
832 const size_t m = a.nops();
834 // The number of terms will be the number of combinatorial compositions,
835 // i.e. the number of unordered arrangements of m nonnegative integers
836 // which sum up to n. It is frequently written as C_n(m) and directly
837 // related with binomial coefficients:
838 result.reserve(binomial(numeric(n+m-1), numeric(m-1)).to_int());
840 intvector k_cum(m-1); // k_cum[l]:=sum(i=0,l,k[l]);
841 intvector upper_limit(m-1);
844 for (size_t l=0; l<m-1; ++l) {
853 for (l=0; l<m-1; ++l) {
854 const ex & b = a.op(l);
855 GINAC_ASSERT(!is_exactly_a<add>(b));
856 GINAC_ASSERT(!is_exactly_a<power>(b) ||
857 !is_exactly_a<numeric>(ex_to<power>(b).exponent) ||
858 !ex_to<numeric>(ex_to<power>(b).exponent).is_pos_integer() ||
859 !is_exactly_a<add>(ex_to<power>(b).basis) ||
860 !is_exactly_a<mul>(ex_to<power>(b).basis) ||
861 !is_exactly_a<power>(ex_to<power>(b).basis));
862 if (is_exactly_a<mul>(b))
863 term.push_back(expand_mul(ex_to<mul>(b), numeric(k[l]), options, true));
865 term.push_back(power(b,k[l]));
868 const ex & b = a.op(l);
869 GINAC_ASSERT(!is_exactly_a<add>(b));
870 GINAC_ASSERT(!is_exactly_a<power>(b) ||
871 !is_exactly_a<numeric>(ex_to<power>(b).exponent) ||
872 !ex_to<numeric>(ex_to<power>(b).exponent).is_pos_integer() ||
873 !is_exactly_a<add>(ex_to<power>(b).basis) ||
874 !is_exactly_a<mul>(ex_to<power>(b).basis) ||
875 !is_exactly_a<power>(ex_to<power>(b).basis));
876 if (is_exactly_a<mul>(b))
877 term.push_back(expand_mul(ex_to<mul>(b), numeric(n-k_cum[m-2]), options, true));
879 term.push_back(power(b,n-k_cum[m-2]));
881 numeric f = binomial(numeric(n),numeric(k[0]));
882 for (l=1; l<m-1; ++l)
883 f *= binomial(numeric(n-k_cum[l-1]),numeric(k[l]));
887 result.push_back(ex((new mul(term))->setflag(status_flags::dynallocated)).expand(options));
891 while ((l>=0) && ((++k[l])>upper_limit[l])) {
897 // recalc k_cum[] and upper_limit[]
898 k_cum[l] = (l==0 ? k[0] : k_cum[l-1]+k[l]);
900 for (size_t i=l+1; i<m-1; ++i)
901 k_cum[i] = k_cum[i-1]+k[i];
903 for (size_t i=l+1; i<m-1; ++i)
904 upper_limit[i] = n-k_cum[i-1];
907 return (new add(result))->setflag(status_flags::dynallocated |
908 status_flags::expanded);
912 /** Special case of power::expand_add. Expands a^2 where a is an add.
913 * @see power::expand_add */
914 ex power::expand_add_2(const add & a, unsigned options) const
917 size_t a_nops = a.nops();
918 sum.reserve((a_nops*(a_nops+1))/2);
919 epvector::const_iterator last = a.seq.end();
921 // power(+(x,...,z;c),2)=power(+(x,...,z;0),2)+2*c*+(x,...,z;0)+c*c
922 // first part: ignore overall_coeff and expand other terms
923 for (epvector::const_iterator cit0=a.seq.begin(); cit0!=last; ++cit0) {
924 const ex & r = cit0->rest;
925 const ex & c = cit0->coeff;
927 GINAC_ASSERT(!is_exactly_a<add>(r));
928 GINAC_ASSERT(!is_exactly_a<power>(r) ||
929 !is_exactly_a<numeric>(ex_to<power>(r).exponent) ||
930 !ex_to<numeric>(ex_to<power>(r).exponent).is_pos_integer() ||
931 !is_exactly_a<add>(ex_to<power>(r).basis) ||
932 !is_exactly_a<mul>(ex_to<power>(r).basis) ||
933 !is_exactly_a<power>(ex_to<power>(r).basis));
935 if (c.is_equal(_ex1)) {
936 if (is_exactly_a<mul>(r)) {
937 sum.push_back(expair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
940 sum.push_back(expair((new power(r,_ex2))->setflag(status_flags::dynallocated),
944 if (is_exactly_a<mul>(r)) {
945 sum.push_back(a.combine_ex_with_coeff_to_pair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
946 ex_to<numeric>(c).power_dyn(*_num2_p)));
948 sum.push_back(a.combine_ex_with_coeff_to_pair((new power(r,_ex2))->setflag(status_flags::dynallocated),
949 ex_to<numeric>(c).power_dyn(*_num2_p)));
953 for (epvector::const_iterator cit1=cit0+1; cit1!=last; ++cit1) {
954 const ex & r1 = cit1->rest;
955 const ex & c1 = cit1->coeff;
956 sum.push_back(a.combine_ex_with_coeff_to_pair((new mul(r,r1))->setflag(status_flags::dynallocated),
957 _num2_p->mul(ex_to<numeric>(c)).mul_dyn(ex_to<numeric>(c1))));
961 GINAC_ASSERT(sum.size()==(a.seq.size()*(a.seq.size()+1))/2);
963 // second part: add terms coming from overall_factor (if != 0)
964 if (!a.overall_coeff.is_zero()) {
965 epvector::const_iterator i = a.seq.begin(), end = a.seq.end();
967 sum.push_back(a.combine_pair_with_coeff_to_pair(*i, ex_to<numeric>(a.overall_coeff).mul_dyn(*_num2_p)));
970 sum.push_back(expair(ex_to<numeric>(a.overall_coeff).power_dyn(*_num2_p),_ex1));
973 GINAC_ASSERT(sum.size()==(a_nops*(a_nops+1))/2);
975 return (new add(sum))->setflag(status_flags::dynallocated | status_flags::expanded);
978 /** Expand factors of m in m^n where m is a mul and n is an integer.
979 * @see power::expand */
980 ex power::expand_mul(const mul & m, const numeric & n, unsigned options, bool from_expand) const
982 GINAC_ASSERT(n.is_integer());
988 // Leave it to multiplication since dummy indices have to be renamed
989 if (get_all_dummy_indices(m).size() > 0 && n.is_positive()) {
991 exvector va = get_all_dummy_indices(m);
992 sort(va.begin(), va.end(), ex_is_less());
994 for (int i=1; i < n.to_int(); i++)
995 result *= rename_dummy_indices_uniquely(va, m);
1000 distrseq.reserve(m.seq.size());
1001 bool need_reexpand = false;
1003 epvector::const_iterator last = m.seq.end();
1004 epvector::const_iterator cit = m.seq.begin();
1006 expair p = m.combine_pair_with_coeff_to_pair(*cit, n);
1007 if (from_expand && is_exactly_a<add>(cit->rest) && ex_to<numeric>(p.coeff).is_pos_integer()) {
1008 // this happens when e.g. (a+b)^(1/2) gets squared and
1009 // the resulting product needs to be reexpanded
1010 need_reexpand = true;
1012 distrseq.push_back(p);
1016 const mul & result = static_cast<const mul &>((new mul(distrseq, ex_to<numeric>(m.overall_coeff).power_dyn(n)))->setflag(status_flags::dynallocated));
1018 return ex(result).expand(options);
1020 return result.setflag(status_flags::expanded);
1024 } // namespace GiNaC