3 * Implementation of GiNaC's symbolic exponentiation (basis^exponent). */
6 * GiNaC Copyright (C) 1999-2010 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
24 #include "expairseq.h"
30 #include "operators.h"
31 #include "inifcns.h" // for log() in power::derivative()
38 #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
74 void power::read_archive(const archive_node &n, lst &sym_lst)
76 inherited::read_archive(n, sym_lst);
77 n.find_ex("basis", basis, sym_lst);
78 n.find_ex("exponent", exponent, sym_lst);
81 void power::archive(archive_node &n) const
83 inherited::archive(n);
84 n.add_ex("basis", basis);
85 n.add_ex("exponent", exponent);
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_cl_N(const print_csrc_cl_N& c, unsigned level) const
167 if (exponent.is_equal(_ex_1)) {
180 void power::do_print_csrc(const print_csrc & c, unsigned level) const
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();
192 print_sym_pow(c, ex_to<symbol>(basis), exp);
195 // <expr>^-1 is printed as "1.0/<expr>" or with the recip() function of CLN
196 } else if (exponent.is_equal(_ex_1)) {
201 // Otherwise, use the pow() function
211 void power::do_print_python(const print_python & c, unsigned level) const
213 print_power(c, "**", "", "", level);
216 void power::do_print_python_repr(const print_python_repr & c, unsigned level) const
218 c.s << class_name() << '(';
225 bool power::info(unsigned inf) const
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) &&
235 case info_flags::rational_function:
236 return exponent.info(info_flags::integer) &&
238 case info_flags::algebraic:
239 return !exponent.info(info_flags::integer) ||
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)
248 else if (flags & status_flags::has_no_indices)
250 else if (basis.info(info_flags::has_indices)) {
251 setflag(status_flags::has_indices);
252 clearflag(status_flags::has_no_indices);
255 clearflag(status_flags::has_indices);
256 setflag(status_flags::has_no_indices);
261 return inherited::info(inf);
264 size_t power::nops() const
269 ex power::op(size_t i) const
273 return i==0 ? basis : exponent;
276 ex power::map(map_function & f) const
278 const ex &mapped_basis = f(basis);
279 const ex &mapped_exponent = f(exponent);
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);
288 bool power::is_polynomial(const ex & var) const
290 if (exponent.has(var))
292 if (!exponent.info(info_flags::nonnegint))
294 return basis.is_polynomial(var);
297 int power::degree(const ex & s) const
299 if (is_equal(ex_to<basic>(s)))
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();
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"));
312 int power::ldegree(const ex & s) const
314 if (is_equal(ex_to<basic>(s)))
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();
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"));
327 ex power::coeff(const ex & s, int n) const
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
339 if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
341 int int_exp = ex_to<numeric>(exponent).to_int();
347 // non-integer exponents are treated as zero
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))
361 * - ^(0,c) -> 0 or exception (depending on the real part of c)
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, 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)
370 * @param level cut-off in recursive evaluation */
371 ex power::eval(int level) const
373 if ((level==1) && (flags & status_flags::evaluated))
375 else if (level == -max_recursion_level)
376 throw(std::runtime_error("max recursion level reached"));
378 const ex & ebasis = level==1 ? basis : basis.eval(level-1);
379 const ex & eexponent = level==1 ? exponent : exponent.eval(level-1);
381 const numeric *num_basis = NULL;
382 const numeric *num_exponent = NULL;
384 if (is_exactly_a<numeric>(ebasis)) {
385 num_basis = &ex_to<numeric>(ebasis);
387 if (is_exactly_a<numeric>(eexponent)) {
388 num_exponent = &ex_to<numeric>(eexponent);
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"));
400 if (eexponent.is_equal(_ex1))
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));
414 if (ebasis.is_equal(_ex1))
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);
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);
425 if ( num_exponent ) {
427 // ^(c1,c2) -> c1^c2 (c1, c2 numeric(),
428 // except if c1,c2 are rational, but c1^c2 is not)
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);
439 const numeric res = num_basis->power(*num_exponent);
440 if (res.is_crational()) {
443 GINAC_ASSERT(!num_exponent->is_integer()); // has been handled by now
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();
452 numeric q = iquo(n, m, r);
453 if (r.is_negative()) {
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);
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);
482 // ^(^(x,c1),c2) -> ^(x,c1*c2)
483 // (c1, c2 numeric(), c2 integer or -1 < c1 <= 1,
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 return power(sub_basis,num_sub_exponent.mul(*num_exponent));
498 // ^(*(x,y,z),c1) -> *(x^c1,y^c1,z^c1) (c1 integer)
499 if (num_exponent->is_integer() && is_exactly_a<mul>(ebasis)) {
500 return expand_mul(ex_to<mul>(ebasis), *num_exponent, 0);
503 // (2*x + 6*y)^(-4) -> 1/16*(x + 3*y)^(-4)
504 if (num_exponent->is_integer() && is_exactly_a<add>(ebasis)) {
505 numeric icont = ebasis.integer_content();
506 const numeric lead_coeff =
507 ex_to<numeric>(ex_to<add>(ebasis).seq.begin()->coeff).div(icont);
509 const bool canonicalizable = lead_coeff.is_integer();
510 const bool unit_normal = lead_coeff.is_pos_integer();
511 if (canonicalizable && (! unit_normal))
512 icont = icont.mul(*_num_1_p);
514 if (canonicalizable && (icont != *_num1_p)) {
515 const add& addref = ex_to<add>(ebasis);
516 add* addp = new add(addref);
517 addp->setflag(status_flags::dynallocated);
518 addp->clearflag(status_flags::hash_calculated);
519 addp->overall_coeff = ex_to<numeric>(addp->overall_coeff).div_dyn(icont);
520 for (epvector::iterator i = addp->seq.begin(); i != addp->seq.end(); ++i)
521 i->coeff = ex_to<numeric>(i->coeff).div_dyn(icont);
523 const numeric c = icont.power(*num_exponent);
524 if (likely(c != *_num1_p))
525 return (new mul(power(*addp, *num_exponent), c))->setflag(status_flags::dynallocated);
527 return power(*addp, *num_exponent);
531 // ^(*(...,x;c1),c2) -> *(^(*(...,x;1),c2),c1^c2) (c1, c2 numeric(), c1>0)
532 // ^(*(...,x;c1),c2) -> *(^(*(...,x;-1),c2),(-c1)^c2) (c1, c2 numeric(), c1<0)
533 if (is_exactly_a<mul>(ebasis)) {
534 GINAC_ASSERT(!num_exponent->is_integer()); // should have been handled above
535 const mul & mulref = ex_to<mul>(ebasis);
536 if (!mulref.overall_coeff.is_equal(_ex1)) {
537 const numeric & num_coeff = ex_to<numeric>(mulref.overall_coeff);
538 if (num_coeff.is_real()) {
539 if (num_coeff.is_positive()) {
540 mul *mulp = new mul(mulref);
541 mulp->overall_coeff = _ex1;
542 mulp->clearflag(status_flags::evaluated);
543 mulp->clearflag(status_flags::hash_calculated);
544 return (new mul(power(*mulp,exponent),
545 power(num_coeff,*num_exponent)))->setflag(status_flags::dynallocated);
547 GINAC_ASSERT(num_coeff.compare(*_num0_p)<0);
548 if (!num_coeff.is_equal(*_num_1_p)) {
549 mul *mulp = new mul(mulref);
550 mulp->overall_coeff = _ex_1;
551 mulp->clearflag(status_flags::evaluated);
552 mulp->clearflag(status_flags::hash_calculated);
553 return (new mul(power(*mulp,exponent),
554 power(abs(num_coeff),*num_exponent)))->setflag(status_flags::dynallocated);
561 // ^(nc,c1) -> ncmul(nc,nc,...) (c1 positive integer, unless nc is a matrix)
562 if (num_exponent->is_pos_integer() &&
563 ebasis.return_type() != return_types::commutative &&
564 !is_a<matrix>(ebasis)) {
565 return ncmul(exvector(num_exponent->to_int(), ebasis), true);
569 if (are_ex_trivially_equal(ebasis,basis) &&
570 are_ex_trivially_equal(eexponent,exponent)) {
573 return (new power(ebasis, eexponent))->setflag(status_flags::dynallocated |
574 status_flags::evaluated);
577 ex power::evalf(int level) const
584 eexponent = exponent;
585 } else if (level == -max_recursion_level) {
586 throw(std::runtime_error("max recursion level reached"));
588 ebasis = basis.evalf(level-1);
589 if (!is_exactly_a<numeric>(exponent))
590 eexponent = exponent.evalf(level-1);
592 eexponent = exponent;
595 return power(ebasis,eexponent);
598 ex power::evalm() const
600 const ex ebasis = basis.evalm();
601 const ex eexponent = exponent.evalm();
602 if (is_a<matrix>(ebasis)) {
603 if (is_exactly_a<numeric>(eexponent)) {
604 return (new matrix(ex_to<matrix>(ebasis).pow(eexponent)))->setflag(status_flags::dynallocated);
607 return (new power(ebasis, eexponent))->setflag(status_flags::dynallocated);
610 bool power::has(const ex & other, unsigned options) const
612 if (!(options & has_options::algebraic))
613 return basic::has(other, options);
614 if (!is_a<power>(other))
615 return basic::has(other, options);
616 if (!exponent.info(info_flags::integer)
617 || !other.op(1).info(info_flags::integer))
618 return basic::has(other, options);
619 if (exponent.info(info_flags::posint)
620 && other.op(1).info(info_flags::posint)
621 && ex_to<numeric>(exponent).to_int()
622 > ex_to<numeric>(other.op(1)).to_int()
623 && basis.match(other.op(0)))
625 if (exponent.info(info_flags::negint)
626 && other.op(1).info(info_flags::negint)
627 && ex_to<numeric>(exponent).to_int()
628 < ex_to<numeric>(other.op(1)).to_int()
629 && basis.match(other.op(0)))
631 return basic::has(other, options);
635 extern bool tryfactsubs(const ex &, const ex &, int &, exmap&);
637 ex power::subs(const exmap & m, unsigned options) const
639 const ex &subsed_basis = basis.subs(m, options);
640 const ex &subsed_exponent = exponent.subs(m, options);
642 if (!are_ex_trivially_equal(basis, subsed_basis)
643 || !are_ex_trivially_equal(exponent, subsed_exponent))
644 return power(subsed_basis, subsed_exponent).subs_one_level(m, options);
646 if (!(options & subs_options::algebraic))
647 return subs_one_level(m, options);
649 for (exmap::const_iterator it = m.begin(); it != m.end(); ++it) {
650 int nummatches = std::numeric_limits<int>::max();
652 if (tryfactsubs(*this, it->first, nummatches, repls)) {
653 ex anum = it->second.subs(repls, subs_options::no_pattern);
654 ex aden = it->first.subs(repls, subs_options::no_pattern);
655 ex result = (*this)*power(anum/aden, nummatches);
656 return (ex_to<basic>(result)).subs_one_level(m, options);
660 return subs_one_level(m, options);
663 ex power::eval_ncmul(const exvector & v) const
665 return inherited::eval_ncmul(v);
668 ex power::conjugate() const
670 // conjugate(pow(x,y))==pow(conjugate(x),conjugate(y)) unless on the
671 // branch cut which runs along the negative real axis.
672 if (basis.info(info_flags::positive)) {
673 ex newexponent = exponent.conjugate();
674 if (are_ex_trivially_equal(exponent, newexponent)) {
677 return (new power(basis, newexponent))->setflag(status_flags::dynallocated);
679 if (exponent.info(info_flags::integer)) {
680 ex newbasis = basis.conjugate();
681 if (are_ex_trivially_equal(basis, newbasis)) {
684 return (new power(newbasis, exponent))->setflag(status_flags::dynallocated);
686 return conjugate_function(*this).hold();
689 ex power::real_part() const
691 if (exponent.info(info_flags::integer)) {
692 ex basis_real = basis.real_part();
693 if (basis_real == basis)
695 realsymbol a("a"),b("b");
697 if (exponent.info(info_flags::posint))
698 result = power(a+I*b,exponent);
700 result = power(a/(a*a+b*b)-I*b/(a*a+b*b),-exponent);
701 result = result.expand();
702 result = result.real_part();
703 result = result.subs(lst( a==basis_real, b==basis.imag_part() ));
707 ex a = basis.real_part();
708 ex b = basis.imag_part();
709 ex c = exponent.real_part();
710 ex d = exponent.imag_part();
711 return power(abs(basis),c)*exp(-d*atan2(b,a))*cos(c*atan2(b,a)+d*log(abs(basis)));
714 ex power::imag_part() const
716 if (exponent.info(info_flags::integer)) {
717 ex basis_real = basis.real_part();
718 if (basis_real == basis)
720 realsymbol a("a"),b("b");
722 if (exponent.info(info_flags::posint))
723 result = power(a+I*b,exponent);
725 result = power(a/(a*a+b*b)-I*b/(a*a+b*b),-exponent);
726 result = result.expand();
727 result = result.imag_part();
728 result = result.subs(lst( a==basis_real, b==basis.imag_part() ));
732 ex a=basis.real_part();
733 ex b=basis.imag_part();
734 ex c=exponent.real_part();
735 ex d=exponent.imag_part();
737 power(abs(basis),c)*exp(-d*atan2(b,a))*sin(c*atan2(b,a)+d*log(abs(basis)));
744 /** Implementation of ex::diff() for a power.
746 ex power::derivative(const symbol & s) const
748 if (is_a<numeric>(exponent)) {
749 // D(b^r) = r * b^(r-1) * D(b) (faster than the formula below)
752 newseq.push_back(expair(basis, exponent - _ex1));
753 newseq.push_back(expair(basis.diff(s), _ex1));
754 return mul(newseq, exponent);
756 // D(b^e) = b^e * (D(e)*ln(b) + e*D(b)/b)
758 add(mul(exponent.diff(s), log(basis)),
759 mul(mul(exponent, basis.diff(s)), power(basis, _ex_1))));
763 int power::compare_same_type(const basic & other) const
765 GINAC_ASSERT(is_exactly_a<power>(other));
766 const power &o = static_cast<const power &>(other);
768 int cmpval = basis.compare(o.basis);
772 return exponent.compare(o.exponent);
775 unsigned power::return_type() const
777 return basis.return_type();
780 return_type_t power::return_type_tinfo() const
782 return basis.return_type_tinfo();
785 ex power::expand(unsigned options) const
787 if (is_a<symbol>(basis) && exponent.info(info_flags::integer)) {
788 // A special case worth optimizing.
789 setflag(status_flags::expanded);
793 const ex expanded_basis = basis.expand(options);
794 const ex expanded_exponent = exponent.expand(options);
796 // x^(a+b) -> x^a * x^b
797 if (is_exactly_a<add>(expanded_exponent)) {
798 const add &a = ex_to<add>(expanded_exponent);
800 distrseq.reserve(a.seq.size() + 1);
801 epvector::const_iterator last = a.seq.end();
802 epvector::const_iterator cit = a.seq.begin();
804 distrseq.push_back(power(expanded_basis, a.recombine_pair_to_ex(*cit)));
808 // Make sure that e.g. (x+y)^(2+a) expands the (x+y)^2 factor
809 if (ex_to<numeric>(a.overall_coeff).is_integer()) {
810 const numeric &num_exponent = ex_to<numeric>(a.overall_coeff);
811 int int_exponent = num_exponent.to_int();
812 if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
813 distrseq.push_back(expand_add(ex_to<add>(expanded_basis), int_exponent, options));
815 distrseq.push_back(power(expanded_basis, a.overall_coeff));
817 distrseq.push_back(power(expanded_basis, a.overall_coeff));
819 // Make sure that e.g. (x+y)^(1+a) -> x*(x+y)^a + y*(x+y)^a
820 ex r = (new mul(distrseq))->setflag(status_flags::dynallocated);
821 return r.expand(options);
824 if (!is_exactly_a<numeric>(expanded_exponent) ||
825 !ex_to<numeric>(expanded_exponent).is_integer()) {
826 if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent)) {
829 return (new power(expanded_basis,expanded_exponent))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
833 // integer numeric exponent
834 const numeric & num_exponent = ex_to<numeric>(expanded_exponent);
835 int int_exponent = num_exponent.to_int();
838 if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
839 return expand_add(ex_to<add>(expanded_basis), int_exponent, options);
841 // (x*y)^n -> x^n * y^n
842 if (is_exactly_a<mul>(expanded_basis))
843 return expand_mul(ex_to<mul>(expanded_basis), num_exponent, options, true);
845 // cannot expand further
846 if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent))
849 return (new power(expanded_basis,expanded_exponent))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
853 // new virtual functions which can be overridden by derived classes
859 // non-virtual functions in this class
862 /** expand a^n where a is an add and n is a positive integer.
863 * @see power::expand */
864 ex power::expand_add(const add & a, int n, unsigned options) const
867 return expand_add_2(a, options);
869 const size_t m = a.nops();
871 // The number of terms will be the number of combinatorial compositions,
872 // i.e. the number of unordered arrangements of m nonnegative integers
873 // which sum up to n. It is frequently written as C_n(m) and directly
874 // related with binomial coefficients:
875 result.reserve(binomial(numeric(n+m-1), numeric(m-1)).to_int());
877 intvector k_cum(m-1); // k_cum[l]:=sum(i=0,l,k[l]);
878 intvector upper_limit(m-1);
880 for (size_t l=0; l<m-1; ++l) {
889 for (std::size_t l = 0; l < m - 1; ++l) {
890 const ex & b = a.op(l);
891 GINAC_ASSERT(!is_exactly_a<add>(b));
892 GINAC_ASSERT(!is_exactly_a<power>(b) ||
893 !is_exactly_a<numeric>(ex_to<power>(b).exponent) ||
894 !ex_to<numeric>(ex_to<power>(b).exponent).is_pos_integer() ||
895 !is_exactly_a<add>(ex_to<power>(b).basis) ||
896 !is_exactly_a<mul>(ex_to<power>(b).basis) ||
897 !is_exactly_a<power>(ex_to<power>(b).basis));
898 if (is_exactly_a<mul>(b))
899 term.push_back(expand_mul(ex_to<mul>(b), numeric(k[l]), options, true));
901 term.push_back(power(b,k[l]));
904 const ex & b = a.op(m - 1);
905 GINAC_ASSERT(!is_exactly_a<add>(b));
906 GINAC_ASSERT(!is_exactly_a<power>(b) ||
907 !is_exactly_a<numeric>(ex_to<power>(b).exponent) ||
908 !ex_to<numeric>(ex_to<power>(b).exponent).is_pos_integer() ||
909 !is_exactly_a<add>(ex_to<power>(b).basis) ||
910 !is_exactly_a<mul>(ex_to<power>(b).basis) ||
911 !is_exactly_a<power>(ex_to<power>(b).basis));
912 if (is_exactly_a<mul>(b))
913 term.push_back(expand_mul(ex_to<mul>(b), numeric(n-k_cum[m-2]), options, true));
915 term.push_back(power(b,n-k_cum[m-2]));
917 numeric f = binomial(numeric(n),numeric(k[0]));
918 for (std::size_t l = 1; l < m - 1; ++l)
919 f *= binomial(numeric(n-k_cum[l-1]),numeric(k[l]));
923 result.push_back(ex((new mul(term))->setflag(status_flags::dynallocated)).expand(options));
927 std::size_t l = m - 2;
928 while ((++k[l]) > upper_limit[l]) {
940 // recalc k_cum[] and upper_limit[]
941 k_cum[l] = (l==0 ? k[0] : k_cum[l-1]+k[l]);
943 for (size_t i=l+1; i<m-1; ++i)
944 k_cum[i] = k_cum[i-1]+k[i];
946 for (size_t i=l+1; i<m-1; ++i)
947 upper_limit[i] = n-k_cum[i-1];
950 return (new add(result))->setflag(status_flags::dynallocated |
951 status_flags::expanded);
955 /** Special case of power::expand_add. Expands a^2 where a is an add.
956 * @see power::expand_add */
957 ex power::expand_add_2(const add & a, unsigned options) const
960 size_t a_nops = a.nops();
961 sum.reserve((a_nops*(a_nops+1))/2);
962 epvector::const_iterator last = a.seq.end();
964 // power(+(x,...,z;c),2)=power(+(x,...,z;0),2)+2*c*+(x,...,z;0)+c*c
965 // first part: ignore overall_coeff and expand other terms
966 for (epvector::const_iterator cit0=a.seq.begin(); cit0!=last; ++cit0) {
967 const ex & r = cit0->rest;
968 const ex & c = cit0->coeff;
970 GINAC_ASSERT(!is_exactly_a<add>(r));
971 GINAC_ASSERT(!is_exactly_a<power>(r) ||
972 !is_exactly_a<numeric>(ex_to<power>(r).exponent) ||
973 !ex_to<numeric>(ex_to<power>(r).exponent).is_pos_integer() ||
974 !is_exactly_a<add>(ex_to<power>(r).basis) ||
975 !is_exactly_a<mul>(ex_to<power>(r).basis) ||
976 !is_exactly_a<power>(ex_to<power>(r).basis));
978 if (c.is_equal(_ex1)) {
979 if (is_exactly_a<mul>(r)) {
980 sum.push_back(expair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
983 sum.push_back(expair((new power(r,_ex2))->setflag(status_flags::dynallocated),
987 if (is_exactly_a<mul>(r)) {
988 sum.push_back(a.combine_ex_with_coeff_to_pair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
989 ex_to<numeric>(c).power_dyn(*_num2_p)));
991 sum.push_back(a.combine_ex_with_coeff_to_pair((new power(r,_ex2))->setflag(status_flags::dynallocated),
992 ex_to<numeric>(c).power_dyn(*_num2_p)));
996 for (epvector::const_iterator cit1=cit0+1; cit1!=last; ++cit1) {
997 const ex & r1 = cit1->rest;
998 const ex & c1 = cit1->coeff;
999 sum.push_back(a.combine_ex_with_coeff_to_pair((new mul(r,r1))->setflag(status_flags::dynallocated),
1000 _num2_p->mul(ex_to<numeric>(c)).mul_dyn(ex_to<numeric>(c1))));
1004 GINAC_ASSERT(sum.size()==(a.seq.size()*(a.seq.size()+1))/2);
1006 // second part: add terms coming from overall_factor (if != 0)
1007 if (!a.overall_coeff.is_zero()) {
1008 epvector::const_iterator i = a.seq.begin(), end = a.seq.end();
1010 sum.push_back(a.combine_pair_with_coeff_to_pair(*i, ex_to<numeric>(a.overall_coeff).mul_dyn(*_num2_p)));
1013 sum.push_back(expair(ex_to<numeric>(a.overall_coeff).power_dyn(*_num2_p),_ex1));
1016 GINAC_ASSERT(sum.size()==(a_nops*(a_nops+1))/2);
1018 return (new add(sum))->setflag(status_flags::dynallocated | status_flags::expanded);
1021 /** Expand factors of m in m^n where m is a mul and n is an integer.
1022 * @see power::expand */
1023 ex power::expand_mul(const mul & m, const numeric & n, unsigned options, bool from_expand) const
1025 GINAC_ASSERT(n.is_integer());
1031 // do not bother to rename indices if there are no any.
1032 if ((!(options & expand_options::expand_rename_idx))
1033 && m.info(info_flags::has_indices))
1034 options |= expand_options::expand_rename_idx;
1035 // Leave it to multiplication since dummy indices have to be renamed
1036 if ((options & expand_options::expand_rename_idx) &&
1037 (get_all_dummy_indices(m).size() > 0) && n.is_positive()) {
1039 exvector va = get_all_dummy_indices(m);
1040 sort(va.begin(), va.end(), ex_is_less());
1042 for (int i=1; i < n.to_int(); i++)
1043 result *= rename_dummy_indices_uniquely(va, m);
1048 distrseq.reserve(m.seq.size());
1049 bool need_reexpand = false;
1051 epvector::const_iterator last = m.seq.end();
1052 epvector::const_iterator cit = m.seq.begin();
1054 expair p = m.combine_pair_with_coeff_to_pair(*cit, n);
1055 if (from_expand && is_exactly_a<add>(cit->rest) && ex_to<numeric>(p.coeff).is_pos_integer()) {
1056 // this happens when e.g. (a+b)^(1/2) gets squared and
1057 // the resulting product needs to be reexpanded
1058 need_reexpand = true;
1060 distrseq.push_back(p);
1064 const mul & result = static_cast<const mul &>((new mul(distrseq, ex_to<numeric>(m.overall_coeff).power_dyn(n)))->setflag(status_flags::dynallocated));
1066 return ex(result).expand(options);
1068 return result.setflag(status_flags::expanded);
1072 GINAC_BIND_UNARCHIVER(power);
1074 } // namespace GiNaC