3 * Implementation of GiNaC's symbolic exponentiation (basis^exponent). */
6 * GiNaC Copyright (C) 1999-2015 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))
57 // default constructor
72 void power::read_archive(const archive_node &n, lst &sym_lst)
74 inherited::read_archive(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);
87 // functions overriding virtual functions from base classes
92 void power::print_power(const print_context & c, const char *powersymbol, const char *openbrace, const char *closebrace, unsigned level) const
94 // Ordinary output of powers using '^' or '**'
95 if (precedence() <= level)
96 c.s << openbrace << '(';
97 basis.print(c, precedence());
100 exponent.print(c, precedence());
102 if (precedence() <= level)
103 c.s << ')' << closebrace;
106 void power::do_print_dflt(const print_dflt & c, unsigned level) const
108 if (exponent.is_equal(_ex1_2)) {
110 // Square roots are printed in a special way
116 print_power(c, "^", "", "", level);
119 void power::do_print_latex(const print_latex & c, unsigned level) const
121 if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_negative()) {
123 // Powers with negative numeric exponents are printed as fractions
125 power(basis, -exponent).eval().print(c);
128 } else if (exponent.is_equal(_ex1_2)) {
130 // Square roots are printed in a special way
136 print_power(c, "^", "{", "}", level);
139 static void print_sym_pow(const print_context & c, const symbol &x, int exp)
141 // Optimal output of integer powers of symbols to aid compiler CSE.
142 // C.f. ISO/IEC 14882:2011, section 1.9 [intro execution], paragraph 15
143 // to learn why such a parenthesation is really necessary.
146 } else if (exp == 2) {
150 } else if (exp & 1) {
153 print_sym_pow(c, x, exp-1);
156 print_sym_pow(c, x, exp >> 1);
158 print_sym_pow(c, x, exp >> 1);
163 void power::do_print_csrc_cl_N(const print_csrc_cl_N& c, unsigned level) const
165 if (exponent.is_equal(_ex_1)) {
178 void power::do_print_csrc(const print_csrc & c, unsigned level) const
180 // Integer powers of symbols are printed in a special, optimized way
181 if (exponent.info(info_flags::integer) &&
182 (is_a<symbol>(basis) || is_a<constant>(basis))) {
183 int exp = ex_to<numeric>(exponent).to_int();
190 print_sym_pow(c, ex_to<symbol>(basis), exp);
193 // <expr>^-1 is printed as "1.0/<expr>" or with the recip() function of CLN
194 } else if (exponent.is_equal(_ex_1)) {
199 // Otherwise, use the pow() function
209 void power::do_print_python(const print_python & c, unsigned level) const
211 print_power(c, "**", "", "", level);
214 void power::do_print_python_repr(const print_python_repr & c, unsigned level) const
216 c.s << class_name() << '(';
223 bool power::info(unsigned inf) const
226 case info_flags::polynomial:
227 case info_flags::integer_polynomial:
228 case info_flags::cinteger_polynomial:
229 case info_flags::rational_polynomial:
230 case info_flags::crational_polynomial:
231 return exponent.info(info_flags::nonnegint) &&
233 case info_flags::rational_function:
234 return exponent.info(info_flags::integer) &&
236 case info_flags::algebraic:
237 return !exponent.info(info_flags::integer) ||
239 case info_flags::expanded:
240 return (flags & status_flags::expanded);
241 case info_flags::positive:
242 return basis.info(info_flags::positive) && exponent.info(info_flags::real);
243 case info_flags::nonnegative:
244 return (basis.info(info_flags::positive) && exponent.info(info_flags::real)) ||
245 (basis.info(info_flags::real) && exponent.info(info_flags::integer) && exponent.info(info_flags::even));
246 case info_flags::has_indices: {
247 if (flags & status_flags::has_indices)
249 else if (flags & status_flags::has_no_indices)
251 else if (basis.info(info_flags::has_indices)) {
252 setflag(status_flags::has_indices);
253 clearflag(status_flags::has_no_indices);
256 clearflag(status_flags::has_indices);
257 setflag(status_flags::has_no_indices);
262 return inherited::info(inf);
265 size_t power::nops() const
270 ex power::op(size_t i) const
274 return i==0 ? basis : exponent;
277 ex power::map(map_function & f) const
279 const ex &mapped_basis = f(basis);
280 const ex &mapped_exponent = f(exponent);
282 if (!are_ex_trivially_equal(basis, mapped_basis)
283 || !are_ex_trivially_equal(exponent, mapped_exponent))
284 return (new power(mapped_basis, mapped_exponent))->setflag(status_flags::dynallocated);
289 bool power::is_polynomial(const ex & var) const
291 if (basis.is_polynomial(var)) {
293 // basis is non-constant polynomial in var
294 return exponent.info(info_flags::nonnegint);
296 // basis is constant in var
297 return !exponent.has(var);
299 // basis is a non-polynomial function of var
303 int power::degree(const ex & s) const
305 if (is_equal(ex_to<basic>(s)))
307 else if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
308 if (basis.is_equal(s))
309 return ex_to<numeric>(exponent).to_int();
311 return basis.degree(s) * ex_to<numeric>(exponent).to_int();
312 } else if (basis.has(s))
313 throw(std::runtime_error("power::degree(): undefined degree because of non-integer exponent"));
318 int power::ldegree(const ex & s) const
320 if (is_equal(ex_to<basic>(s)))
322 else if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
323 if (basis.is_equal(s))
324 return ex_to<numeric>(exponent).to_int();
326 return basis.ldegree(s) * ex_to<numeric>(exponent).to_int();
327 } else if (basis.has(s))
328 throw(std::runtime_error("power::ldegree(): undefined degree because of non-integer exponent"));
333 ex power::coeff(const ex & s, int n) const
335 if (is_equal(ex_to<basic>(s)))
336 return n==1 ? _ex1 : _ex0;
337 else if (!basis.is_equal(s)) {
338 // basis not equal to s
345 if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
347 int int_exp = ex_to<numeric>(exponent).to_int();
353 // non-integer exponents are treated as zero
362 /** Perform automatic term rewriting rules in this class. In the following
363 * x, x1, x2,... stand for a symbolic variables of type ex and c, c1, c2...
364 * stand for such expressions that contain a plain number.
365 * - ^(x,0) -> 1 (also handles ^(0,0))
367 * - ^(0,c) -> 0 or exception (depending on the real part of c)
369 * - ^(c1,c2) -> *(c1^n,c1^(c2-n)) (so that 0<(c2-n)<1, try to evaluate roots, possibly in numerator and denominator of c1)
370 * - ^(^(x,c1),c2) -> ^(x,c1*c2) if x is positive and c1 is real.
371 * - ^(^(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!)
372 * - ^(*(x,y,z),c) -> *(x^c,y^c,z^c) (if c integer)
373 * - ^(*(x,c1),c2) -> ^(x,c2)*c1^c2 (c1>0)
374 * - ^(*(x,c1),c2) -> ^(-x,c2)*c1^c2 (c1<0)
376 * @param level cut-off in recursive evaluation */
377 ex power::eval(int level) const
379 if ((level==1) && (flags & status_flags::evaluated))
381 else if (level == -max_recursion_level)
382 throw(std::runtime_error("max recursion level reached"));
384 const ex & ebasis = level==1 ? basis : basis.eval(level-1);
385 const ex & eexponent = level==1 ? exponent : exponent.eval(level-1);
387 const numeric *num_basis = nullptr;
388 const numeric *num_exponent = nullptr;
390 if (is_exactly_a<numeric>(ebasis)) {
391 num_basis = &ex_to<numeric>(ebasis);
393 if (is_exactly_a<numeric>(eexponent)) {
394 num_exponent = &ex_to<numeric>(eexponent);
397 // ^(x,0) -> 1 (0^0 also handled here)
398 if (eexponent.is_zero()) {
399 if (ebasis.is_zero())
400 throw (std::domain_error("power::eval(): pow(0,0) is undefined"));
406 if (eexponent.is_equal(_ex1))
409 // ^(0,c1) -> 0 or exception (depending on real value of c1)
410 if ( ebasis.is_zero() && num_exponent ) {
411 if ((num_exponent->real()).is_zero())
412 throw (std::domain_error("power::eval(): pow(0,I) is undefined"));
413 else if ((num_exponent->real()).is_negative())
414 throw (pole_error("power::eval(): division by zero",1));
420 if (ebasis.is_equal(_ex1))
423 // power of a function calculated by separate rules defined for this function
424 if (is_exactly_a<function>(ebasis))
425 return ex_to<function>(ebasis).power(eexponent);
427 // Turn (x^c)^d into x^(c*d) in the case that x is positive and c is real.
428 if (is_exactly_a<power>(ebasis) && ebasis.op(0).info(info_flags::positive) && ebasis.op(1).info(info_flags::real))
429 return power(ebasis.op(0), ebasis.op(1) * eexponent);
431 if ( num_exponent ) {
433 // ^(c1,c2) -> c1^c2 (c1, c2 numeric(),
434 // except if c1,c2 are rational, but c1^c2 is not)
436 const bool basis_is_crational = num_basis->is_crational();
437 const bool exponent_is_crational = num_exponent->is_crational();
438 if (!basis_is_crational || !exponent_is_crational) {
439 // return a plain float
440 return (new numeric(num_basis->power(*num_exponent)))->setflag(status_flags::dynallocated |
441 status_flags::evaluated |
442 status_flags::expanded);
445 const numeric res = num_basis->power(*num_exponent);
446 if (res.is_crational()) {
449 GINAC_ASSERT(!num_exponent->is_integer()); // has been handled by now
451 // ^(c1,n/m) -> *(c1^q,c1^(n/m-q)), 0<(n/m-q)<1, q integer
452 if (basis_is_crational && exponent_is_crational
453 && num_exponent->is_real()
454 && !num_exponent->is_integer()) {
455 const numeric n = num_exponent->numer();
456 const numeric m = num_exponent->denom();
458 numeric q = iquo(n, m, r);
459 if (r.is_negative()) {
463 if (q.is_zero()) { // the exponent was in the allowed range 0<(n/m)<1
464 if (num_basis->is_rational() && !num_basis->is_integer()) {
465 // try it for numerator and denominator separately, in order to
466 // partially simplify things like (5/8)^(1/3) -> 1/2*5^(1/3)
467 const numeric bnum = num_basis->numer();
468 const numeric bden = num_basis->denom();
469 const numeric res_bnum = bnum.power(*num_exponent);
470 const numeric res_bden = bden.power(*num_exponent);
471 if (res_bnum.is_integer())
472 return (new mul(power(bden,-*num_exponent),res_bnum))->setflag(status_flags::dynallocated | status_flags::evaluated);
473 if (res_bden.is_integer())
474 return (new mul(power(bnum,*num_exponent),res_bden.inverse()))->setflag(status_flags::dynallocated | status_flags::evaluated);
478 // assemble resulting product, but allowing for a re-evaluation,
479 // because otherwise we'll end up with something like
480 // (7/8)^(4/3) -> 7/8*(1/2*7^(1/3))
481 // instead of 7/16*7^(1/3).
482 ex prod = power(*num_basis,r.div(m));
483 return prod*power(*num_basis,q);
488 // ^(^(x,c1),c2) -> ^(x,c1*c2)
489 // (c1, c2 numeric(), c2 integer or -1 < c1 <= 1 or (c1=-1 and c2>0),
490 // case c1==1 should not happen, see below!)
491 if (is_exactly_a<power>(ebasis)) {
492 const power & sub_power = ex_to<power>(ebasis);
493 const ex & sub_basis = sub_power.basis;
494 const ex & sub_exponent = sub_power.exponent;
495 if (is_exactly_a<numeric>(sub_exponent)) {
496 const numeric & num_sub_exponent = ex_to<numeric>(sub_exponent);
497 GINAC_ASSERT(num_sub_exponent!=numeric(1));
498 if (num_exponent->is_integer() || (abs(num_sub_exponent) - (*_num1_p)).is_negative() ||
499 (num_sub_exponent == *_num_1_p && num_exponent->is_positive())) {
500 return power(sub_basis,num_sub_exponent.mul(*num_exponent));
505 // ^(*(x,y,z),c1) -> *(x^c1,y^c1,z^c1) (c1 integer)
506 if (num_exponent->is_integer() && is_exactly_a<mul>(ebasis)) {
507 return expand_mul(ex_to<mul>(ebasis), *num_exponent, 0);
510 // (2*x + 6*y)^(-4) -> 1/16*(x + 3*y)^(-4)
511 if (num_exponent->is_integer() && is_exactly_a<add>(ebasis)) {
512 numeric icont = ebasis.integer_content();
513 const numeric lead_coeff =
514 ex_to<numeric>(ex_to<add>(ebasis).seq.begin()->coeff).div(icont);
516 const bool canonicalizable = lead_coeff.is_integer();
517 const bool unit_normal = lead_coeff.is_pos_integer();
518 if (canonicalizable && (! unit_normal))
519 icont = icont.mul(*_num_1_p);
521 if (canonicalizable && (icont != *_num1_p)) {
522 const add& addref = ex_to<add>(ebasis);
523 add* addp = new add(addref);
524 addp->setflag(status_flags::dynallocated);
525 addp->clearflag(status_flags::hash_calculated);
526 addp->overall_coeff = ex_to<numeric>(addp->overall_coeff).div_dyn(icont);
527 for (auto & i : addp->seq)
528 i.coeff = ex_to<numeric>(i.coeff).div_dyn(icont);
530 const numeric c = icont.power(*num_exponent);
531 if (likely(c != *_num1_p))
532 return (new mul(power(*addp, *num_exponent), c))->setflag(status_flags::dynallocated);
534 return power(*addp, *num_exponent);
538 // ^(*(...,x;c1),c2) -> *(^(*(...,x;1),c2),c1^c2) (c1, c2 numeric(), c1>0)
539 // ^(*(...,x;c1),c2) -> *(^(*(...,x;-1),c2),(-c1)^c2) (c1, c2 numeric(), c1<0)
540 if (is_exactly_a<mul>(ebasis)) {
541 GINAC_ASSERT(!num_exponent->is_integer()); // should have been handled above
542 const mul & mulref = ex_to<mul>(ebasis);
543 if (!mulref.overall_coeff.is_equal(_ex1)) {
544 const numeric & num_coeff = ex_to<numeric>(mulref.overall_coeff);
545 if (num_coeff.is_real()) {
546 if (num_coeff.is_positive()) {
547 mul *mulp = new mul(mulref);
548 mulp->overall_coeff = _ex1;
549 mulp->setflag(status_flags::dynallocated);
550 mulp->clearflag(status_flags::evaluated);
551 mulp->clearflag(status_flags::hash_calculated);
552 return (new mul(power(*mulp,exponent),
553 power(num_coeff,*num_exponent)))->setflag(status_flags::dynallocated);
555 GINAC_ASSERT(num_coeff.compare(*_num0_p)<0);
556 if (!num_coeff.is_equal(*_num_1_p)) {
557 mul *mulp = new mul(mulref);
558 mulp->overall_coeff = _ex_1;
559 mulp->setflag(status_flags::dynallocated);
560 mulp->clearflag(status_flags::evaluated);
561 mulp->clearflag(status_flags::hash_calculated);
562 return (new mul(power(*mulp,exponent),
563 power(abs(num_coeff),*num_exponent)))->setflag(status_flags::dynallocated);
570 // ^(nc,c1) -> ncmul(nc,nc,...) (c1 positive integer, unless nc is a matrix)
571 if (num_exponent->is_pos_integer() &&
572 ebasis.return_type() != return_types::commutative &&
573 !is_a<matrix>(ebasis)) {
574 return ncmul(exvector(num_exponent->to_int(), ebasis), true);
578 if (are_ex_trivially_equal(ebasis,basis) &&
579 are_ex_trivially_equal(eexponent,exponent)) {
582 return (new power(ebasis, eexponent))->setflag(status_flags::dynallocated |
583 status_flags::evaluated);
586 ex power::evalf(int level) const
593 eexponent = exponent;
594 } else if (level == -max_recursion_level) {
595 throw(std::runtime_error("max recursion level reached"));
597 ebasis = basis.evalf(level-1);
598 if (!is_exactly_a<numeric>(exponent))
599 eexponent = exponent.evalf(level-1);
601 eexponent = exponent;
604 return power(ebasis,eexponent);
607 ex power::evalm() const
609 const ex ebasis = basis.evalm();
610 const ex eexponent = exponent.evalm();
611 if (is_a<matrix>(ebasis)) {
612 if (is_exactly_a<numeric>(eexponent)) {
613 return (new matrix(ex_to<matrix>(ebasis).pow(eexponent)))->setflag(status_flags::dynallocated);
616 return (new power(ebasis, eexponent))->setflag(status_flags::dynallocated);
619 bool power::has(const ex & other, unsigned options) const
621 if (!(options & has_options::algebraic))
622 return basic::has(other, options);
623 if (!is_a<power>(other))
624 return basic::has(other, options);
625 if (!exponent.info(info_flags::integer) ||
626 !other.op(1).info(info_flags::integer))
627 return basic::has(other, options);
628 if (exponent.info(info_flags::posint) &&
629 other.op(1).info(info_flags::posint) &&
630 ex_to<numeric>(exponent) > ex_to<numeric>(other.op(1)) &&
631 basis.match(other.op(0)))
633 if (exponent.info(info_flags::negint) &&
634 other.op(1).info(info_flags::negint) &&
635 ex_to<numeric>(exponent) < ex_to<numeric>(other.op(1)) &&
636 basis.match(other.op(0)))
638 return basic::has(other, options);
642 extern bool tryfactsubs(const ex &, const ex &, int &, exmap&);
644 ex power::subs(const exmap & m, unsigned options) const
646 const ex &subsed_basis = basis.subs(m, options);
647 const ex &subsed_exponent = exponent.subs(m, options);
649 if (!are_ex_trivially_equal(basis, subsed_basis)
650 || !are_ex_trivially_equal(exponent, subsed_exponent))
651 return power(subsed_basis, subsed_exponent).subs_one_level(m, options);
653 if (!(options & subs_options::algebraic))
654 return subs_one_level(m, options);
656 for (auto & it : m) {
657 int nummatches = std::numeric_limits<int>::max();
659 if (tryfactsubs(*this, it.first, nummatches, repls)) {
660 ex anum = it.second.subs(repls, subs_options::no_pattern);
661 ex aden = it.first.subs(repls, subs_options::no_pattern);
662 ex result = (*this)*power(anum/aden, nummatches);
663 return (ex_to<basic>(result)).subs_one_level(m, options);
667 return subs_one_level(m, options);
670 ex power::eval_ncmul(const exvector & v) const
672 return inherited::eval_ncmul(v);
675 ex power::conjugate() const
677 // conjugate(pow(x,y))==pow(conjugate(x),conjugate(y)) unless on the
678 // branch cut which runs along the negative real axis.
679 if (basis.info(info_flags::positive)) {
680 ex newexponent = exponent.conjugate();
681 if (are_ex_trivially_equal(exponent, newexponent)) {
684 return (new power(basis, newexponent))->setflag(status_flags::dynallocated);
686 if (exponent.info(info_flags::integer)) {
687 ex newbasis = basis.conjugate();
688 if (are_ex_trivially_equal(basis, newbasis)) {
691 return (new power(newbasis, exponent))->setflag(status_flags::dynallocated);
693 return conjugate_function(*this).hold();
696 ex power::real_part() const
698 // basis == a+I*b, exponent == c+I*d
699 const ex a = basis.real_part();
700 const ex c = exponent.real_part();
701 if (basis.is_equal(a) && exponent.is_equal(c)) {
706 const ex b = basis.imag_part();
707 if (exponent.info(info_flags::integer)) {
708 // Re((a+I*b)^c) w/ c ∈ ℤ
709 long N = ex_to<numeric>(c).to_long();
710 // Use real terms in Binomial expansion to construct
711 // Re(expand(power(a+I*b, N))).
712 long NN = N > 0 ? N : -N;
713 ex numer = N > 0 ? _ex1 : power(power(a,2) + power(b,2), NN);
715 for (long n = 0; n <= NN; n += 2) {
716 ex term = binomial(NN, n) * power(a, NN-n) * power(b, n) / numer;
718 result += term; // sign: I^n w/ n == 4*m
720 result -= term; // sign: I^n w/ n == 4*m+2
726 // Re((a+I*b)^(c+I*d))
727 const ex d = exponent.imag_part();
728 return power(abs(basis),c)*exp(-d*atan2(b,a))*cos(c*atan2(b,a)+d*log(abs(basis)));
731 ex power::imag_part() const
733 const ex a = basis.real_part();
734 const ex c = exponent.real_part();
735 if (basis.is_equal(a) && exponent.is_equal(c)) {
740 const ex b = basis.imag_part();
741 if (exponent.info(info_flags::integer)) {
742 // Im((a+I*b)^c) w/ c ∈ ℤ
743 long N = ex_to<numeric>(c).to_long();
744 // Use imaginary terms in Binomial expansion to construct
745 // Im(expand(power(a+I*b, N))).
746 long p = N > 0 ? 1 : 3; // modulus for positive sign
747 long NN = N > 0 ? N : -N;
748 ex numer = N > 0 ? _ex1 : power(power(a,2) + power(b,2), NN);
750 for (long n = 1; n <= NN; n += 2) {
751 ex term = binomial(NN, n) * power(a, NN-n) * power(b, n) / numer;
753 result += term; // sign: I^n w/ n == 4*m+p
755 result -= term; // sign: I^n w/ n == 4*m+2+p
761 // Im((a+I*b)^(c+I*d))
762 const ex d = exponent.imag_part();
763 return power(abs(basis),c)*exp(-d*atan2(b,a))*sin(c*atan2(b,a)+d*log(abs(basis)));
768 /** Implementation of ex::diff() for a power.
770 ex power::derivative(const symbol & s) const
772 if (is_a<numeric>(exponent)) {
773 // D(b^r) = r * b^(r-1) * D(b) (faster than the formula below)
776 newseq.push_back(expair(basis, exponent - _ex1));
777 newseq.push_back(expair(basis.diff(s), _ex1));
778 return mul(newseq, exponent);
780 // D(b^e) = b^e * (D(e)*ln(b) + e*D(b)/b)
782 add(mul(exponent.diff(s), log(basis)),
783 mul(mul(exponent, basis.diff(s)), power(basis, _ex_1))));
787 int power::compare_same_type(const basic & other) const
789 GINAC_ASSERT(is_exactly_a<power>(other));
790 const power &o = static_cast<const power &>(other);
792 int cmpval = basis.compare(o.basis);
796 return exponent.compare(o.exponent);
799 unsigned power::return_type() const
801 return basis.return_type();
804 return_type_t power::return_type_tinfo() const
806 return basis.return_type_tinfo();
809 ex power::expand(unsigned options) const
811 if (is_a<symbol>(basis) && exponent.info(info_flags::integer)) {
812 // A special case worth optimizing.
813 setflag(status_flags::expanded);
817 // (x*p)^c -> x^c * p^c, if p>0
818 // makes sense before expanding the basis
819 if (is_exactly_a<mul>(basis) && !basis.info(info_flags::indefinite)) {
820 const mul &m = ex_to<mul>(basis);
823 prodseq.reserve(m.seq.size() + 1);
824 powseq.reserve(m.seq.size() + 1);
827 // search for positive/negative factors
828 for (auto & cit : m.seq) {
829 ex e=m.recombine_pair_to_ex(cit);
830 if (e.info(info_flags::positive))
831 prodseq.push_back(pow(e, exponent).expand(options));
832 else if (e.info(info_flags::negative)) {
833 prodseq.push_back(pow(-e, exponent).expand(options));
836 powseq.push_back(cit);
839 // take care on the numeric coefficient
840 ex coeff=(possign? _ex1 : _ex_1);
841 if (m.overall_coeff.info(info_flags::positive) && m.overall_coeff != _ex1)
842 prodseq.push_back(power(m.overall_coeff, exponent));
843 else if (m.overall_coeff.info(info_flags::negative) && m.overall_coeff != _ex_1)
844 prodseq.push_back(power(-m.overall_coeff, exponent));
846 coeff *= m.overall_coeff;
848 // If positive/negative factors are found, then extract them.
849 // In either case we set a flag to avoid the second run on a part
850 // which does not have positive/negative terms.
851 if (prodseq.size() > 0) {
852 ex newbasis = coeff*mul(powseq);
853 ex_to<basic>(newbasis).setflag(status_flags::purely_indefinite);
854 return ((new mul(prodseq))->setflag(status_flags::dynallocated)*(new power(newbasis, exponent))->setflag(status_flags::dynallocated).expand(options)).expand(options);
856 ex_to<basic>(basis).setflag(status_flags::purely_indefinite);
859 const ex expanded_basis = basis.expand(options);
860 const ex expanded_exponent = exponent.expand(options);
862 // x^(a+b) -> x^a * x^b
863 if (is_exactly_a<add>(expanded_exponent)) {
864 const add &a = ex_to<add>(expanded_exponent);
866 distrseq.reserve(a.seq.size() + 1);
867 for (auto & cit : a.seq) {
868 distrseq.push_back(power(expanded_basis, a.recombine_pair_to_ex(cit)));
871 // Make sure that e.g. (x+y)^(2+a) expands the (x+y)^2 factor
872 if (ex_to<numeric>(a.overall_coeff).is_integer()) {
873 const numeric &num_exponent = ex_to<numeric>(a.overall_coeff);
874 int int_exponent = num_exponent.to_int();
875 if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
876 distrseq.push_back(expand_add(ex_to<add>(expanded_basis), int_exponent, options));
878 distrseq.push_back(power(expanded_basis, a.overall_coeff));
880 distrseq.push_back(power(expanded_basis, a.overall_coeff));
882 // Make sure that e.g. (x+y)^(1+a) -> x*(x+y)^a + y*(x+y)^a
883 ex r = (new mul(distrseq))->setflag(status_flags::dynallocated);
884 return r.expand(options);
887 if (!is_exactly_a<numeric>(expanded_exponent) ||
888 !ex_to<numeric>(expanded_exponent).is_integer()) {
889 if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent)) {
892 return (new power(expanded_basis,expanded_exponent))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
896 // integer numeric exponent
897 const numeric & num_exponent = ex_to<numeric>(expanded_exponent);
898 int int_exponent = num_exponent.to_int();
901 if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
902 return expand_add(ex_to<add>(expanded_basis), int_exponent, options);
904 // (x*y)^n -> x^n * y^n
905 if (is_exactly_a<mul>(expanded_basis))
906 return expand_mul(ex_to<mul>(expanded_basis), num_exponent, options, true);
908 // cannot expand further
909 if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent))
912 return (new power(expanded_basis,expanded_exponent))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
916 // new virtual functions which can be overridden by derived classes
922 // non-virtual functions in this class
925 namespace { // anonymous namespace for power::expand_add() helpers
927 /** Helper class to generate all bounded combinatorial partitions of an integer
928 * n with exactly m parts (including zero parts) in non-decreasing order.
930 class partition_generator {
932 // Partitions n into m parts, not including zero parts.
933 // (Cf. OEIS sequence A008284; implementation adapted from Jörg Arndt's
937 // partition: x[1] + x[2] + ... + x[m] = n and sentinel x[0] == 0
941 mpartition2(unsigned n_, unsigned m_)
942 : x(m_+1), n(n_), m(m_)
944 for (int k=1; k<m; ++k)
948 bool next_partition()
950 int u = x[m]; // last element
959 return false; // current is last
970 int m; // number of parts 0<m<=n
971 mutable std::vector<int> partition; // current partition
973 partition_generator(unsigned n_, unsigned m_)
974 : mpgen(n_, 1), m(m_), partition(m_)
976 // returns current partition in non-decreasing order, padded with zeros
977 const std::vector<int>& current() const
979 for (int i = 0; i < m - mpgen.m; ++i)
980 partition[i] = 0; // pad with zeros
982 for (int i = m - mpgen.m; i < m; ++i)
983 partition[i] = mpgen.x[i - m + mpgen.m + 1];
989 if (!mpgen.next_partition()) {
990 if (mpgen.m == m || mpgen.m == mpgen.n)
991 return false; // current is last
992 // increment number of parts
993 mpgen = mpartition2(mpgen.n, mpgen.m + 1);
999 /** Helper class to generate all compositions of a partition of an integer n,
1000 * starting with the compositions which has non-decreasing order.
1002 class composition_generator {
1004 // Generates all distinct permutations of a multiset.
1005 // (Based on Aaron Williams' algorithm 1 from "Loopless Generation of
1006 // Multiset Permutations using a Constant Number of Variables by Prefix
1007 // Shifts." <http://webhome.csc.uvic.ca/~haron/CoolMulti.pdf>)
1009 // element of singly linked list
1013 element(int val, element* n)
1014 : value(val), next(n) {}
1016 { // recurses down to the end of the singly linked list
1020 element *head, *i, *after_i;
1021 // NB: Partition must be sorted in non-decreasing order.
1022 explicit coolmulti(const std::vector<int>& partition)
1023 : head(nullptr), i(nullptr), after_i(nullptr)
1025 for (unsigned n = 0; n < partition.size(); ++n) {
1026 head = new element(partition[n], head);
1033 { // deletes singly linked list
1036 void next_permutation()
1039 if (after_i->next != nullptr && i->value >= after_i->next->value)
1043 element *k = before_k->next;
1044 before_k->next = k->next;
1046 if (k->value < head->value)
1051 bool finished() const
1053 return after_i->next == nullptr && after_i->value >= head->value;
1056 bool atend; // needed for simplifying iteration over permutations
1057 bool trivial; // likewise, true if all elements are equal
1058 mutable std::vector<int> composition; // current compositions
1060 explicit composition_generator(const std::vector<int>& partition)
1061 : cmgen(partition), atend(false), trivial(true), composition(partition.size())
1063 for (unsigned i=1; i<partition.size(); ++i)
1064 trivial = trivial && (partition[0] == partition[i]);
1066 const std::vector<int>& current() const
1068 coolmulti::element* it = cmgen.head;
1070 while (it != nullptr) {
1071 composition[i] = it->value;
1079 // This ugly contortion is needed because the original coolmulti
1080 // algorithm requires code duplication of the payload procedure,
1081 // one before the loop and one inside it.
1082 if (trivial || atend)
1084 cmgen.next_permutation();
1085 atend = cmgen.finished();
1090 /** Helper function to compute the multinomial coefficient n!/(p1!*p2!*...*pk!)
1091 * where n = p1+p2+...+pk, i.e. p is a partition of n.
1094 multinomial_coefficient(const std::vector<int> p)
1096 numeric n = 0, d = 1;
1097 for (auto & it : p) {
1099 d *= factorial(numeric(it));
1101 return factorial(numeric(n)) / d;
1104 } // anonymous namespace
1106 /** expand a^n where a is an add and n is a positive integer.
1107 * @see power::expand */
1108 ex power::expand_add(const add & a, int n, unsigned options) const
1110 // The special case power(+(x,...y;x),2) can be optimized better.
1112 return expand_add_2(a, options);
1116 // Consider base as the sum of all symbolic terms and the overall numeric
1117 // coefficient and apply the binomial theorem:
1118 // S = power(+(x,...,z;c),n)
1119 // = power(+(+(x,...,z;0);c),n)
1120 // = sum(binomial(n,k)*power(+(x,...,z;0),k)*c^(n-k), k=1..n) + c^n
1121 // Then, apply the multinomial theorem to expand all power(+(x,...,z;0),k):
1122 // The multinomial theorem is computed by an outer loop over all
1123 // partitions of the exponent and an inner loop over all compositions of
1124 // that partition. This method makes the expansion a combinatorial
1125 // problem and allows us to directly construct the expanded sum and also
1126 // to re-use the multinomial coefficients (since they depend only on the
1127 // partition, not on the composition).
1129 // multinomial power(+(x,y,z;0),3) example:
1130 // partition : compositions : multinomial coefficient
1131 // [0,0,3] : [3,0,0],[0,3,0],[0,0,3] : 3!/(3!*0!*0!) = 1
1132 // [0,1,2] : [2,1,0],[1,2,0],[2,0,1],... : 3!/(2!*1!*0!) = 3
1133 // [1,1,1] : [1,1,1] : 3!/(1!*1!*1!) = 6
1134 // => (x + y + z)^3 =
1136 // + 3*x^2*y + 3*x*y^2 + 3*y^2*z + 3*y*z^2 + 3*x*z^2 + 3*x^2*z
1139 // multinomial power(+(x,y,z;0),4) example:
1140 // partition : compositions : multinomial coefficient
1141 // [0,0,4] : [4,0,0],[0,4,0],[0,0,4] : 4!/(4!*0!*0!) = 1
1142 // [0,1,3] : [3,1,0],[1,3,0],[3,0,1],... : 4!/(3!*1!*0!) = 4
1143 // [0,2,2] : [2,2,0],[2,0,2],[0,2,2] : 4!/(2!*2!*0!) = 6
1144 // [1,1,2] : [2,1,1],[1,2,1],[1,1,2] : 4!/(2!*1!*1!) = 12
1145 // (no [1,1,1,1] partition since it has too many parts)
1146 // => (x + y + z)^4 =
1148 // + 4*x^3*y + 4*x*y^3 + 4*y^3*z + 4*y*z^3 + 4*x*z^3 + 4*x^3*z
1149 // + 6*x^2*y^2 + 6*y^2*z^2 + 6*x^2*z^2
1150 // + 12*x^2*y*z + 12*x*y^2*z + 12*x*y*z^2
1154 // for k from 0 to n:
1155 // f = c^(n-k)*binomial(n,k)
1156 // for p in all partitions of n with m parts (including zero parts):
1157 // h = f * multinomial coefficient of p
1158 // for c in all compositions of p:
1160 // for e in all elements of c:
1166 // The number of terms will be the number of combinatorial compositions,
1167 // i.e. the number of unordered arrangements of m nonnegative integers
1168 // which sum up to n. It is frequently written as C_n(m) and directly
1169 // related with binomial coefficients: binomial(n+m-1,m-1).
1170 size_t result_size = binomial(numeric(n+a.nops()-1), numeric(a.nops()-1)).to_int();
1171 if (!a.overall_coeff.is_zero()) {
1172 // the result's overall_coeff is one of the terms
1175 result.reserve(result_size);
1177 // Iterate over all terms in binomial expansion of
1178 // S = power(+(x,...,z;c),n)
1179 // = sum(binomial(n,k)*power(+(x,...,z;0),k)*c^(n-k), k=1..n) + c^n
1180 for (int k = 1; k <= n; ++k) {
1181 numeric binomial_coefficient; // binomial(n,k)*c^(n-k)
1182 if (a.overall_coeff.is_zero()) {
1183 // degenerate case with zero overall_coeff:
1184 // apply multinomial theorem directly to power(+(x,...z;0),n)
1185 binomial_coefficient = 1;
1190 binomial_coefficient = binomial(numeric(n), numeric(k)) * pow(ex_to<numeric>(a.overall_coeff), numeric(n-k));
1193 // Multinomial expansion of power(+(x,...,z;0),k)*c^(n-k):
1194 // Iterate over all partitions of k with exactly as many parts as
1195 // there are symbolic terms in the basis (including zero parts).
1196 partition_generator partitions(k, a.seq.size());
1198 const std::vector<int>& partition = partitions.current();
1199 const numeric coeff = multinomial_coefficient(partition) * binomial_coefficient;
1201 // Iterate over all compositions of the current partition.
1202 composition_generator compositions(partition);
1204 const std::vector<int>& exponent = compositions.current();
1207 numeric factor = coeff;
1208 for (unsigned i = 0; i < exponent.size(); ++i) {
1209 const ex & r = a.seq[i].rest;
1210 const ex & c = a.seq[i].coeff;
1211 GINAC_ASSERT(!is_exactly_a<add>(r));
1212 GINAC_ASSERT(!is_exactly_a<power>(r) ||
1213 !is_exactly_a<numeric>(ex_to<power>(r).exponent) ||
1214 !ex_to<numeric>(ex_to<power>(r).exponent).is_pos_integer() ||
1215 !is_exactly_a<add>(ex_to<power>(r).basis) ||
1216 !is_exactly_a<mul>(ex_to<power>(r).basis) ||
1217 !is_exactly_a<power>(ex_to<power>(r).basis));
1218 if (exponent[i] == 0) {
1220 } else if (exponent[i] == 1) {
1223 factor = factor.mul(ex_to<numeric>(c));
1224 } else { // general case exponent[i] > 1
1225 term.push_back((new power(r, exponent[i]))->setflag(status_flags::dynallocated));
1226 factor = factor.mul(ex_to<numeric>(c).power(exponent[i]));
1229 result.push_back(a.combine_ex_with_coeff_to_pair(mul(term).expand(options), factor));
1230 } while (compositions.next());
1231 } while (partitions.next());
1234 GINAC_ASSERT(result.size() == result_size);
1236 if (a.overall_coeff.is_zero()) {
1237 return (new add(result))->setflag(status_flags::dynallocated |
1238 status_flags::expanded);
1240 return (new add(result, ex_to<numeric>(a.overall_coeff).power(n)))->setflag(status_flags::dynallocated |
1241 status_flags::expanded);
1246 /** Special case of power::expand_add. Expands a^2 where a is an add.
1247 * @see power::expand_add */
1248 ex power::expand_add_2(const add & a, unsigned options) const
1251 size_t a_nops = a.nops();
1252 sum.reserve((a_nops*(a_nops+1))/2);
1253 epvector::const_iterator last = a.seq.end();
1255 // power(+(x,...,z;c),2)=power(+(x,...,z;0),2)+2*c*+(x,...,z;0)+c*c
1256 // first part: ignore overall_coeff and expand other terms
1257 for (epvector::const_iterator cit0=a.seq.begin(); cit0!=last; ++cit0) {
1258 const ex & r = cit0->rest;
1259 const ex & c = cit0->coeff;
1261 GINAC_ASSERT(!is_exactly_a<add>(r));
1262 GINAC_ASSERT(!is_exactly_a<power>(r) ||
1263 !is_exactly_a<numeric>(ex_to<power>(r).exponent) ||
1264 !ex_to<numeric>(ex_to<power>(r).exponent).is_pos_integer() ||
1265 !is_exactly_a<add>(ex_to<power>(r).basis) ||
1266 !is_exactly_a<mul>(ex_to<power>(r).basis) ||
1267 !is_exactly_a<power>(ex_to<power>(r).basis));
1269 if (c.is_equal(_ex1)) {
1270 if (is_exactly_a<mul>(r)) {
1271 sum.push_back(a.combine_ex_with_coeff_to_pair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
1274 sum.push_back(a.combine_ex_with_coeff_to_pair((new power(r,_ex2))->setflag(status_flags::dynallocated),
1278 if (is_exactly_a<mul>(r)) {
1279 sum.push_back(a.combine_ex_with_coeff_to_pair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
1280 ex_to<numeric>(c).power_dyn(*_num2_p)));
1282 sum.push_back(a.combine_ex_with_coeff_to_pair((new power(r,_ex2))->setflag(status_flags::dynallocated),
1283 ex_to<numeric>(c).power_dyn(*_num2_p)));
1287 for (epvector::const_iterator cit1=cit0+1; cit1!=last; ++cit1) {
1288 const ex & r1 = cit1->rest;
1289 const ex & c1 = cit1->coeff;
1290 sum.push_back(a.combine_ex_with_coeff_to_pair(mul(r,r1).expand(options),
1291 _num2_p->mul(ex_to<numeric>(c)).mul_dyn(ex_to<numeric>(c1))));
1295 GINAC_ASSERT(sum.size()==(a.seq.size()*(a.seq.size()+1))/2);
1297 // second part: add terms coming from overall_coeff (if != 0)
1298 if (!a.overall_coeff.is_zero()) {
1299 epvector::const_iterator i = a.seq.begin(), end = a.seq.end();
1301 sum.push_back(a.combine_pair_with_coeff_to_pair(*i, ex_to<numeric>(a.overall_coeff).mul_dyn(*_num2_p)));
1304 sum.push_back(expair(ex_to<numeric>(a.overall_coeff).power_dyn(*_num2_p),_ex1));
1307 GINAC_ASSERT(sum.size()==(a_nops*(a_nops+1))/2);
1309 return (new add(sum))->setflag(status_flags::dynallocated | status_flags::expanded);
1312 /** Expand factors of m in m^n where m is a mul and n is an integer.
1313 * @see power::expand */
1314 ex power::expand_mul(const mul & m, const numeric & n, unsigned options, bool from_expand) const
1316 GINAC_ASSERT(n.is_integer());
1322 // do not bother to rename indices if there are no any.
1323 if (!(options & expand_options::expand_rename_idx) &&
1324 m.info(info_flags::has_indices))
1325 options |= expand_options::expand_rename_idx;
1326 // Leave it to multiplication since dummy indices have to be renamed
1327 if ((options & expand_options::expand_rename_idx) &&
1328 (get_all_dummy_indices(m).size() > 0) && n.is_positive()) {
1330 exvector va = get_all_dummy_indices(m);
1331 sort(va.begin(), va.end(), ex_is_less());
1333 for (int i=1; i < n.to_int(); i++)
1334 result *= rename_dummy_indices_uniquely(va, m);
1339 distrseq.reserve(m.seq.size());
1340 bool need_reexpand = false;
1342 for (auto & cit : m.seq) {
1343 expair p = m.combine_pair_with_coeff_to_pair(cit, n);
1344 if (from_expand && is_exactly_a<add>(cit.rest) && ex_to<numeric>(p.coeff).is_pos_integer()) {
1345 // this happens when e.g. (a+b)^(1/2) gets squared and
1346 // the resulting product needs to be reexpanded
1347 need_reexpand = true;
1349 distrseq.push_back(p);
1352 const mul & result = static_cast<const mul &>((new mul(distrseq, ex_to<numeric>(m.overall_coeff).power_dyn(n)))->setflag(status_flags::dynallocated));
1354 return ex(result).expand(options);
1356 return result.setflag(status_flags::expanded);
1360 GINAC_BIND_UNARCHIVER(power);
1362 } // namespace GiNaC