3 * Implementation of GiNaC's symbolic exponentiation (basis^exponent). */
6 * GiNaC Copyright (C) 1999-2018 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"
49 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(power, basic,
50 print_func<print_dflt>(&power::do_print_dflt).
51 print_func<print_latex>(&power::do_print_latex).
52 print_func<print_csrc>(&power::do_print_csrc).
53 print_func<print_python>(&power::do_print_python).
54 print_func<print_python_repr>(&power::do_print_python_repr).
55 print_func<print_csrc_cl_N>(&power::do_print_csrc_cl_N))
58 // default constructor
73 void power::read_archive(const archive_node &n, lst &sym_lst)
75 inherited::read_archive(n, sym_lst);
76 n.find_ex("basis", basis, sym_lst);
77 n.find_ex("exponent", exponent, sym_lst);
80 void power::archive(archive_node &n) const
82 inherited::archive(n);
83 n.add_ex("basis", basis);
84 n.add_ex("exponent", exponent);
88 // functions overriding virtual functions from base classes
93 void power::print_power(const print_context & c, const char *powersymbol, const char *openbrace, const char *closebrace, unsigned level) const
95 // Ordinary output of powers using '^' or '**'
96 if (precedence() <= level)
97 c.s << openbrace << '(';
98 basis.print(c, precedence());
101 exponent.print(c, precedence());
103 if (precedence() <= level)
104 c.s << ')' << closebrace;
107 void power::do_print_dflt(const print_dflt & c, unsigned level) const
109 if (exponent.is_equal(_ex1_2)) {
111 // Square roots are printed in a special way
117 print_power(c, "^", "", "", level);
120 void power::do_print_latex(const print_latex & c, unsigned level) const
122 if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_negative()) {
124 // Powers with negative numeric exponents are printed as fractions
126 power(basis, -exponent).eval().print(c);
129 } else if (exponent.is_equal(_ex1_2)) {
131 // Square roots are printed in a special way
137 print_power(c, "^", "{", "}", level);
140 static void print_sym_pow(const print_context & c, const symbol &x, int exp)
142 // Optimal output of integer powers of symbols to aid compiler CSE.
143 // C.f. ISO/IEC 14882:2011, section 1.9 [intro execution], paragraph 15
144 // to learn why such a parenthesation is really necessary.
147 } else if (exp == 2) {
151 } else if (exp & 1) {
154 print_sym_pow(c, x, exp-1);
157 print_sym_pow(c, x, exp >> 1);
159 print_sym_pow(c, x, exp >> 1);
164 void power::do_print_csrc_cl_N(const print_csrc_cl_N& c, unsigned level) const
166 if (exponent.is_equal(_ex_1)) {
179 void power::do_print_csrc(const print_csrc & c, unsigned level) const
181 // Integer powers of symbols are printed in a special, optimized way
182 if (exponent.info(info_flags::integer) &&
183 (is_a<symbol>(basis) || is_a<constant>(basis))) {
184 int exp = ex_to<numeric>(exponent).to_int();
191 print_sym_pow(c, ex_to<symbol>(basis), exp);
194 // <expr>^-1 is printed as "1.0/<expr>" or with the recip() function of CLN
195 } else if (exponent.is_equal(_ex_1)) {
200 // Otherwise, use the pow() function
210 void power::do_print_python(const print_python & c, unsigned level) const
212 print_power(c, "**", "", "", level);
215 void power::do_print_python_repr(const print_python_repr & c, unsigned level) const
217 c.s << class_name() << '(';
224 bool power::info(unsigned inf) const
227 case info_flags::polynomial:
228 case info_flags::integer_polynomial:
229 case info_flags::cinteger_polynomial:
230 case info_flags::rational_polynomial:
231 case info_flags::crational_polynomial:
232 return basis.info(inf) && exponent.info(info_flags::nonnegint);
233 case info_flags::rational_function:
234 return basis.info(inf) && exponent.info(info_flags::integer);
235 case info_flags::real:
236 return basis.info(inf) && exponent.info(info_flags::integer);
237 case info_flags::expanded:
238 return (flags & status_flags::expanded);
239 case info_flags::positive:
240 return basis.info(info_flags::positive) && exponent.info(info_flags::real);
241 case info_flags::nonnegative:
242 return (basis.info(info_flags::positive) && exponent.info(info_flags::real)) ||
243 (basis.info(info_flags::real) && exponent.info(info_flags::even));
244 case info_flags::has_indices: {
245 if (flags & status_flags::has_indices)
247 else if (flags & status_flags::has_no_indices)
249 else if (basis.info(info_flags::has_indices)) {
250 setflag(status_flags::has_indices);
251 clearflag(status_flags::has_no_indices);
254 clearflag(status_flags::has_indices);
255 setflag(status_flags::has_no_indices);
260 return inherited::info(inf);
263 size_t power::nops() const
268 ex power::op(size_t i) const
272 return i==0 ? basis : exponent;
275 ex power::map(map_function & f) const
277 const ex &mapped_basis = f(basis);
278 const ex &mapped_exponent = f(exponent);
280 if (!are_ex_trivially_equal(basis, mapped_basis)
281 || !are_ex_trivially_equal(exponent, mapped_exponent))
282 return dynallocate<power>(mapped_basis, mapped_exponent);
287 bool power::is_polynomial(const ex & var) const
289 if (basis.is_polynomial(var)) {
291 // basis is non-constant polynomial in var
292 return exponent.info(info_flags::nonnegint);
294 // basis is constant in var
295 return !exponent.has(var);
297 // basis is a non-polynomial function of var
301 int power::degree(const ex & s) const
303 if (is_equal(ex_to<basic>(s)))
305 else if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
306 if (basis.is_equal(s))
307 return ex_to<numeric>(exponent).to_int();
309 return basis.degree(s) * ex_to<numeric>(exponent).to_int();
310 } else if (basis.has(s))
311 throw(std::runtime_error("power::degree(): undefined degree because of non-integer exponent"));
316 int power::ldegree(const ex & s) const
318 if (is_equal(ex_to<basic>(s)))
320 else if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
321 if (basis.is_equal(s))
322 return ex_to<numeric>(exponent).to_int();
324 return basis.ldegree(s) * ex_to<numeric>(exponent).to_int();
325 } else if (basis.has(s))
326 throw(std::runtime_error("power::ldegree(): undefined degree because of non-integer exponent"));
331 ex power::coeff(const ex & s, int n) const
333 if (is_equal(ex_to<basic>(s)))
334 return n==1 ? _ex1 : _ex0;
335 else if (!basis.is_equal(s)) {
336 // basis not equal to s
343 if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
345 int int_exp = ex_to<numeric>(exponent).to_int();
351 // non-integer exponents are treated as zero
360 /** Perform automatic term rewriting rules in this class. In the following
361 * x, x1, x2,... stand for a symbolic variables of type ex and c, c1, c2...
362 * stand for such expressions that contain a plain number.
363 * - ^(x,0) -> 1 (also handles ^(0,0))
365 * - ^(0,c) -> 0 or exception (depending on the real part of c)
367 * - ^(c1,c2) -> *(c1^n,c1^(c2-n)) (so that 0<(c2-n)<1, try to evaluate roots, possibly in numerator and denominator of c1)
368 * - ^(^(x,c1),c2) -> ^(x,c1*c2) if x is positive and c1 is real.
369 * - ^(^(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!)
370 * - ^(*(x,y,z),c) -> *(x^c,y^c,z^c) (if c integer)
371 * - ^(*(x,c1),c2) -> ^(x,c2)*c1^c2 (c1>0)
372 * - ^(*(x,c1),c2) -> ^(-x,c2)*c1^c2 (c1<0)
374 ex power::eval() const
376 if (flags & status_flags::evaluated)
379 const numeric *num_basis = nullptr;
380 const numeric *num_exponent = nullptr;
382 if (is_exactly_a<numeric>(basis)) {
383 num_basis = &ex_to<numeric>(basis);
385 if (is_exactly_a<numeric>(exponent)) {
386 num_exponent = &ex_to<numeric>(exponent);
389 // ^(x,0) -> 1 (0^0 also handled here)
390 if (exponent.is_zero()) {
392 throw (std::domain_error("power::eval(): pow(0,0) is undefined"));
398 if (exponent.is_equal(_ex1))
401 // ^(0,c1) -> 0 or exception (depending on real value of c1)
402 if (basis.is_zero() && num_exponent) {
403 if ((num_exponent->real()).is_zero())
404 throw (std::domain_error("power::eval(): pow(0,I) is undefined"));
405 else if ((num_exponent->real()).is_negative())
406 throw (pole_error("power::eval(): division by zero",1));
412 if (basis.is_equal(_ex1))
415 // power of a function calculated by separate rules defined for this function
416 if (is_exactly_a<function>(basis))
417 return ex_to<function>(basis).power(exponent);
419 // Turn (x^c)^d into x^(c*d) in the case that x is positive and c is real.
420 if (is_exactly_a<power>(basis) && basis.op(0).info(info_flags::positive) && basis.op(1).info(info_flags::real))
421 return dynallocate<power>(basis.op(0), basis.op(1) * exponent);
423 if ( num_exponent ) {
425 // ^(c1,c2) -> c1^c2 (c1, c2 numeric(),
426 // except if c1,c2 are rational, but c1^c2 is not)
428 const bool basis_is_crational = num_basis->is_crational();
429 const bool exponent_is_crational = num_exponent->is_crational();
430 if (!basis_is_crational || !exponent_is_crational) {
431 // return a plain float
432 return dynallocate<numeric>(num_basis->power(*num_exponent));
435 const numeric res = num_basis->power(*num_exponent);
436 if (res.is_crational()) {
439 GINAC_ASSERT(!num_exponent->is_integer()); // has been handled by now
441 // ^(c1,n/m) -> *(c1^q,c1^(n/m-q)), 0<(n/m-q)<1, q integer
442 if (basis_is_crational && exponent_is_crational
443 && num_exponent->is_real()
444 && !num_exponent->is_integer()) {
445 const numeric n = num_exponent->numer();
446 const numeric m = num_exponent->denom();
448 numeric q = iquo(n, m, r);
449 if (r.is_negative()) {
453 if (q.is_zero()) { // the exponent was in the allowed range 0<(n/m)<1
454 if (num_basis->is_rational() && !num_basis->is_integer()) {
455 // try it for numerator and denominator separately, in order to
456 // partially simplify things like (5/8)^(1/3) -> 1/2*5^(1/3)
457 const numeric bnum = num_basis->numer();
458 const numeric bden = num_basis->denom();
459 const numeric res_bnum = bnum.power(*num_exponent);
460 const numeric res_bden = bden.power(*num_exponent);
461 if (res_bnum.is_integer())
462 return dynallocate<mul>(dynallocate<power>(bden,-*num_exponent),res_bnum).setflag(status_flags::evaluated);
463 if (res_bden.is_integer())
464 return dynallocate<mul>(dynallocate<power>(bnum,*num_exponent),res_bden.inverse()).setflag(status_flags::evaluated);
468 // assemble resulting product, but allowing for a re-evaluation,
469 // because otherwise we'll end up with something like
470 // (7/8)^(4/3) -> 7/8*(1/2*7^(1/3))
471 // instead of 7/16*7^(1/3).
472 return pow(basis, r.div(m)) * pow(basis, q);
477 // ^(^(x,c1),c2) -> ^(x,c1*c2)
478 // (c1, c2 numeric(), c2 integer or -1 < c1 <= 1 or (c1=-1 and c2>0),
479 // case c1==1 should not happen, see below!)
480 if (is_exactly_a<power>(basis)) {
481 const power & sub_power = ex_to<power>(basis);
482 const ex & sub_basis = sub_power.basis;
483 const ex & sub_exponent = sub_power.exponent;
484 if (is_exactly_a<numeric>(sub_exponent)) {
485 const numeric & num_sub_exponent = ex_to<numeric>(sub_exponent);
486 GINAC_ASSERT(num_sub_exponent!=numeric(1));
487 if (num_exponent->is_integer() || (abs(num_sub_exponent) - (*_num1_p)).is_negative() ||
488 (num_sub_exponent == *_num_1_p && num_exponent->is_positive())) {
489 return dynallocate<power>(sub_basis, num_sub_exponent.mul(*num_exponent));
494 // ^(*(x,y,z),c1) -> *(x^c1,y^c1,z^c1) (c1 integer)
495 if (num_exponent->is_integer() && is_exactly_a<mul>(basis)) {
496 return expand_mul(ex_to<mul>(basis), *num_exponent, false);
499 // (2*x + 6*y)^(-4) -> 1/16*(x + 3*y)^(-4)
500 if (num_exponent->is_integer() && is_exactly_a<add>(basis)) {
501 numeric icont = basis.integer_content();
502 const numeric lead_coeff =
503 ex_to<numeric>(ex_to<add>(basis).seq.begin()->coeff).div(icont);
505 const bool canonicalizable = lead_coeff.is_integer();
506 const bool unit_normal = lead_coeff.is_pos_integer();
507 if (canonicalizable && (! unit_normal))
508 icont = icont.mul(*_num_1_p);
510 if (canonicalizable && (icont != *_num1_p)) {
511 const add& addref = ex_to<add>(basis);
512 add & addp = dynallocate<add>(addref);
513 addp.clearflag(status_flags::hash_calculated);
514 addp.overall_coeff = ex_to<numeric>(addp.overall_coeff).div_dyn(icont);
515 for (auto & i : addp.seq)
516 i.coeff = ex_to<numeric>(i.coeff).div_dyn(icont);
518 const numeric c = icont.power(*num_exponent);
519 if (likely(c != *_num1_p))
520 return dynallocate<mul>(dynallocate<power>(addp, *num_exponent), c);
522 return dynallocate<power>(addp, *num_exponent);
526 // ^(*(...,x;c1),c2) -> *(^(*(...,x;1),c2),c1^c2) (c1, c2 numeric(), c1>0)
527 // ^(*(...,x;c1),c2) -> *(^(*(...,x;-1),c2),(-c1)^c2) (c1, c2 numeric(), c1<0)
528 if (is_exactly_a<mul>(basis)) {
529 GINAC_ASSERT(!num_exponent->is_integer()); // should have been handled above
530 const mul & mulref = ex_to<mul>(basis);
531 if (!mulref.overall_coeff.is_equal(_ex1)) {
532 const numeric & num_coeff = ex_to<numeric>(mulref.overall_coeff);
533 if (num_coeff.is_real()) {
534 if (num_coeff.is_positive()) {
535 mul & mulp = dynallocate<mul>(mulref);
536 mulp.overall_coeff = _ex1;
537 mulp.clearflag(status_flags::evaluated | status_flags::hash_calculated);
538 return dynallocate<mul>(dynallocate<power>(mulp, exponent),
539 dynallocate<power>(num_coeff, *num_exponent));
541 GINAC_ASSERT(num_coeff.compare(*_num0_p)<0);
542 if (!num_coeff.is_equal(*_num_1_p)) {
543 mul & mulp = dynallocate<mul>(mulref);
544 mulp.overall_coeff = _ex_1;
545 mulp.clearflag(status_flags::evaluated | status_flags::hash_calculated);
546 return dynallocate<mul>(dynallocate<power>(mulp, exponent),
547 dynallocate<power>(abs(num_coeff), *num_exponent));
554 // ^(nc,c1) -> ncmul(nc,nc,...) (c1 positive integer, unless nc is a matrix)
555 if (num_exponent->is_pos_integer() &&
556 basis.return_type() != return_types::commutative &&
557 !is_a<matrix>(basis)) {
558 return ncmul(exvector(num_exponent->to_int(), basis));
565 ex power::evalf() const
567 ex ebasis = basis.evalf();
570 if (!is_exactly_a<numeric>(exponent))
571 eexponent = exponent.evalf();
573 eexponent = exponent;
575 return dynallocate<power>(ebasis, eexponent);
578 ex power::evalm() const
580 const ex ebasis = basis.evalm();
581 const ex eexponent = exponent.evalm();
582 if (is_a<matrix>(ebasis)) {
583 if (is_exactly_a<numeric>(eexponent)) {
584 return dynallocate<matrix>(ex_to<matrix>(ebasis).pow(eexponent));
587 return dynallocate<power>(ebasis, eexponent);
590 bool power::has(const ex & other, unsigned options) const
592 if (!(options & has_options::algebraic))
593 return basic::has(other, options);
594 if (!is_a<power>(other))
595 return basic::has(other, options);
596 if (!exponent.info(info_flags::integer) ||
597 !other.op(1).info(info_flags::integer))
598 return basic::has(other, options);
599 if (exponent.info(info_flags::posint) &&
600 other.op(1).info(info_flags::posint) &&
601 ex_to<numeric>(exponent) > ex_to<numeric>(other.op(1)) &&
602 basis.match(other.op(0)))
604 if (exponent.info(info_flags::negint) &&
605 other.op(1).info(info_flags::negint) &&
606 ex_to<numeric>(exponent) < ex_to<numeric>(other.op(1)) &&
607 basis.match(other.op(0)))
609 return basic::has(other, options);
613 extern bool tryfactsubs(const ex &, const ex &, int &, exmap&);
615 ex power::subs(const exmap & m, unsigned options) const
617 const ex &subsed_basis = basis.subs(m, options);
618 const ex &subsed_exponent = exponent.subs(m, options);
620 if (!are_ex_trivially_equal(basis, subsed_basis)
621 || !are_ex_trivially_equal(exponent, subsed_exponent))
622 return power(subsed_basis, subsed_exponent).subs_one_level(m, options);
624 if (!(options & subs_options::algebraic))
625 return subs_one_level(m, options);
627 for (auto & it : m) {
628 int nummatches = std::numeric_limits<int>::max();
630 if (tryfactsubs(*this, it.first, nummatches, repls)) {
631 ex anum = it.second.subs(repls, subs_options::no_pattern);
632 ex aden = it.first.subs(repls, subs_options::no_pattern);
633 ex result = (*this) * pow(anum/aden, nummatches);
634 return (ex_to<basic>(result)).subs_one_level(m, options);
638 return subs_one_level(m, options);
641 ex power::eval_ncmul(const exvector & v) const
643 return inherited::eval_ncmul(v);
646 ex power::conjugate() const
648 // conjugate(pow(x,y))==pow(conjugate(x),conjugate(y)) unless on the
649 // branch cut which runs along the negative real axis.
650 if (basis.info(info_flags::positive)) {
651 ex newexponent = exponent.conjugate();
652 if (are_ex_trivially_equal(exponent, newexponent)) {
655 return dynallocate<power>(basis, newexponent);
657 if (exponent.info(info_flags::integer)) {
658 ex newbasis = basis.conjugate();
659 if (are_ex_trivially_equal(basis, newbasis)) {
662 return dynallocate<power>(newbasis, exponent);
664 return conjugate_function(*this).hold();
667 ex power::real_part() const
669 // basis == a+I*b, exponent == c+I*d
670 const ex a = basis.real_part();
671 const ex c = exponent.real_part();
672 if (basis.is_equal(a) && exponent.is_equal(c) &&
673 (a.info(info_flags::nonnegative) || c.info(info_flags::integer))) {
678 const ex b = basis.imag_part();
679 if (exponent.info(info_flags::integer)) {
680 // Re((a+I*b)^c) w/ c ∈ ℤ
681 long N = ex_to<numeric>(c).to_long();
682 // Use real terms in Binomial expansion to construct
683 // Re(expand(pow(a+I*b, N))).
684 long NN = N > 0 ? N : -N;
685 ex numer = N > 0 ? _ex1 : pow(pow(a,2) + pow(b,2), NN);
687 for (long n = 0; n <= NN; n += 2) {
688 ex term = binomial(NN, n) * pow(a, NN-n) * pow(b, n) / numer;
690 result += term; // sign: I^n w/ n == 4*m
692 result -= term; // sign: I^n w/ n == 4*m+2
698 // Re((a+I*b)^(c+I*d))
699 const ex d = exponent.imag_part();
700 return pow(abs(basis),c) * exp(-d*atan2(b,a)) * cos(c*atan2(b,a)+d*log(abs(basis)));
703 ex power::imag_part() const
705 // basis == a+I*b, exponent == c+I*d
706 const ex a = basis.real_part();
707 const ex c = exponent.real_part();
708 if (basis.is_equal(a) && exponent.is_equal(c) &&
709 (a.info(info_flags::nonnegative) || c.info(info_flags::integer))) {
714 const ex b = basis.imag_part();
715 if (exponent.info(info_flags::integer)) {
716 // Im((a+I*b)^c) w/ c ∈ ℤ
717 long N = ex_to<numeric>(c).to_long();
718 // Use imaginary terms in Binomial expansion to construct
719 // Im(expand(pow(a+I*b, N))).
720 long p = N > 0 ? 1 : 3; // modulus for positive sign
721 long NN = N > 0 ? N : -N;
722 ex numer = N > 0 ? _ex1 : pow(pow(a,2) + pow(b,2), NN);
724 for (long n = 1; n <= NN; n += 2) {
725 ex term = binomial(NN, n) * pow(a, NN-n) * pow(b, n) / numer;
727 result += term; // sign: I^n w/ n == 4*m+p
729 result -= term; // sign: I^n w/ n == 4*m+2+p
735 // Im((a+I*b)^(c+I*d))
736 const ex d = exponent.imag_part();
737 return pow(abs(basis),c) * exp(-d*atan2(b,a)) * sin(c*atan2(b,a)+d*log(abs(basis)));
742 /** Implementation of ex::diff() for a power.
744 ex power::derivative(const symbol & s) const
746 if (is_a<numeric>(exponent)) {
747 // D(b^r) = r * b^(r-1) * D(b) (faster than the formula below)
748 const epvector newseq = {expair(basis, exponent - _ex1), expair(basis.diff(s), _ex1)};
749 return dynallocate<mul>(std::move(newseq), exponent);
751 // D(b^e) = b^e * (D(e)*ln(b) + e*D(b)/b)
752 return *this * (exponent.diff(s)*log(basis) + exponent*basis.diff(s)*pow(basis, _ex_1));
756 int power::compare_same_type(const basic & other) const
758 GINAC_ASSERT(is_exactly_a<power>(other));
759 const power &o = static_cast<const power &>(other);
761 int cmpval = basis.compare(o.basis);
765 return exponent.compare(o.exponent);
768 unsigned power::return_type() const
770 return basis.return_type();
773 return_type_t power::return_type_tinfo() const
775 return basis.return_type_tinfo();
778 ex power::expand(unsigned options) const
780 if (is_a<symbol>(basis) && exponent.info(info_flags::integer)) {
781 // A special case worth optimizing.
782 setflag(status_flags::expanded);
786 // (x*p)^c -> x^c * p^c, if p>0
787 // makes sense before expanding the basis
788 if (is_exactly_a<mul>(basis) && !basis.info(info_flags::indefinite)) {
789 const mul &m = ex_to<mul>(basis);
792 prodseq.reserve(m.seq.size() + 1);
793 powseq.reserve(m.seq.size() + 1);
796 // search for positive/negative factors
797 for (auto & cit : m.seq) {
798 ex e=m.recombine_pair_to_ex(cit);
799 if (e.info(info_flags::positive))
800 prodseq.push_back(pow(e, exponent).expand(options));
801 else if (e.info(info_flags::negative)) {
802 prodseq.push_back(pow(-e, exponent).expand(options));
805 powseq.push_back(cit);
808 // take care on the numeric coefficient
809 ex coeff=(possign? _ex1 : _ex_1);
810 if (m.overall_coeff.info(info_flags::positive) && m.overall_coeff != _ex1)
811 prodseq.push_back(pow(m.overall_coeff, exponent));
812 else if (m.overall_coeff.info(info_flags::negative) && m.overall_coeff != _ex_1)
813 prodseq.push_back(pow(-m.overall_coeff, exponent));
815 coeff *= m.overall_coeff;
817 // If positive/negative factors are found, then extract them.
818 // In either case we set a flag to avoid the second run on a part
819 // which does not have positive/negative terms.
820 if (prodseq.size() > 0) {
821 ex newbasis = dynallocate<mul>(std::move(powseq), coeff);
822 ex_to<basic>(newbasis).setflag(status_flags::purely_indefinite);
823 return dynallocate<mul>(std::move(prodseq)) * pow(newbasis, exponent);
825 ex_to<basic>(basis).setflag(status_flags::purely_indefinite);
828 const ex expanded_basis = basis.expand(options);
829 const ex expanded_exponent = exponent.expand(options);
831 // x^(a+b) -> x^a * x^b
832 if (is_exactly_a<add>(expanded_exponent)) {
833 const add &a = ex_to<add>(expanded_exponent);
835 distrseq.reserve(a.seq.size() + 1);
836 for (auto & cit : a.seq) {
837 distrseq.push_back(pow(expanded_basis, a.recombine_pair_to_ex(cit)));
840 // Make sure that e.g. (x+y)^(2+a) expands the (x+y)^2 factor
841 if (ex_to<numeric>(a.overall_coeff).is_integer()) {
842 const numeric &num_exponent = ex_to<numeric>(a.overall_coeff);
843 long int_exponent = num_exponent.to_int();
844 if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
845 distrseq.push_back(expand_add(ex_to<add>(expanded_basis), int_exponent, options));
847 distrseq.push_back(pow(expanded_basis, a.overall_coeff));
849 distrseq.push_back(pow(expanded_basis, a.overall_coeff));
851 // Make sure that e.g. (x+y)^(1+a) -> x*(x+y)^a + y*(x+y)^a
852 ex r = dynallocate<mul>(distrseq);
853 return r.expand(options);
856 if (!is_exactly_a<numeric>(expanded_exponent) ||
857 !ex_to<numeric>(expanded_exponent).is_integer()) {
858 if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent)) {
861 return dynallocate<power>(expanded_basis, expanded_exponent).setflag(options == 0 ? status_flags::expanded : 0);
865 // integer numeric exponent
866 const numeric & num_exponent = ex_to<numeric>(expanded_exponent);
867 long int_exponent = num_exponent.to_long();
870 if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
871 return expand_add(ex_to<add>(expanded_basis), int_exponent, options);
873 // (x*y)^n -> x^n * y^n
874 if (is_exactly_a<mul>(expanded_basis))
875 return expand_mul(ex_to<mul>(expanded_basis), num_exponent, options, true);
877 // cannot expand further
878 if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent))
881 return dynallocate<power>(expanded_basis, expanded_exponent).setflag(options == 0 ? status_flags::expanded : 0);
885 // new virtual functions which can be overridden by derived classes
891 // non-virtual functions in this class
894 /** expand a^n where a is an add and n is a positive integer.
895 * @see power::expand */
896 ex power::expand_add(const add & a, long n, unsigned options)
898 // The special case power(+(x,...y;x),2) can be optimized better.
900 return expand_add_2(a, options);
904 // Consider base as the sum of all symbolic terms and the overall numeric
905 // coefficient and apply the binomial theorem:
906 // S = power(+(x,...,z;c),n)
907 // = power(+(+(x,...,z;0);c),n)
908 // = sum(binomial(n,k)*power(+(x,...,z;0),k)*c^(n-k), k=1..n) + c^n
909 // Then, apply the multinomial theorem to expand all power(+(x,...,z;0),k):
910 // The multinomial theorem is computed by an outer loop over all
911 // partitions of the exponent and an inner loop over all compositions of
912 // that partition. This method makes the expansion a combinatorial
913 // problem and allows us to directly construct the expanded sum and also
914 // to re-use the multinomial coefficients (since they depend only on the
915 // partition, not on the composition).
917 // multinomial power(+(x,y,z;0),3) example:
918 // partition : compositions : multinomial coefficient
919 // [0,0,3] : [3,0,0],[0,3,0],[0,0,3] : 3!/(3!*0!*0!) = 1
920 // [0,1,2] : [2,1,0],[1,2,0],[2,0,1],... : 3!/(2!*1!*0!) = 3
921 // [1,1,1] : [1,1,1] : 3!/(1!*1!*1!) = 6
922 // => (x + y + z)^3 =
924 // + 3*x^2*y + 3*x*y^2 + 3*y^2*z + 3*y*z^2 + 3*x*z^2 + 3*x^2*z
927 // multinomial power(+(x,y,z;0),4) example:
928 // partition : compositions : multinomial coefficient
929 // [0,0,4] : [4,0,0],[0,4,0],[0,0,4] : 4!/(4!*0!*0!) = 1
930 // [0,1,3] : [3,1,0],[1,3,0],[3,0,1],... : 4!/(3!*1!*0!) = 4
931 // [0,2,2] : [2,2,0],[2,0,2],[0,2,2] : 4!/(2!*2!*0!) = 6
932 // [1,1,2] : [2,1,1],[1,2,1],[1,1,2] : 4!/(2!*1!*1!) = 12
933 // (no [1,1,1,1] partition since it has too many parts)
934 // => (x + y + z)^4 =
936 // + 4*x^3*y + 4*x*y^3 + 4*y^3*z + 4*y*z^3 + 4*x*z^3 + 4*x^3*z
937 // + 6*x^2*y^2 + 6*y^2*z^2 + 6*x^2*z^2
938 // + 12*x^2*y*z + 12*x*y^2*z + 12*x*y*z^2
942 // for k from 0 to n:
943 // f = c^(n-k)*binomial(n,k)
944 // for p in all partitions of n with m parts (including zero parts):
945 // h = f * multinomial coefficient of p
946 // for c in all compositions of p:
948 // for e in all elements of c:
954 // The number of terms will be the number of combinatorial compositions,
955 // i.e. the number of unordered arrangements of m nonnegative integers
956 // which sum up to n. It is frequently written as C_n(m) and directly
957 // related with binomial coefficients: binomial(n+m-1,m-1).
958 size_t result_size = binomial(numeric(n+a.nops()-1), numeric(a.nops()-1)).to_long();
959 if (!a.overall_coeff.is_zero()) {
960 // the result's overall_coeff is one of the terms
963 result.reserve(result_size);
965 // Iterate over all terms in binomial expansion of
966 // S = power(+(x,...,z;c),n)
967 // = sum(binomial(n,k)*power(+(x,...,z;0),k)*c^(n-k), k=1..n) + c^n
968 for (int k = 1; k <= n; ++k) {
969 numeric binomial_coefficient; // binomial(n,k)*c^(n-k)
970 if (a.overall_coeff.is_zero()) {
971 // degenerate case with zero overall_coeff:
972 // apply multinomial theorem directly to power(+(x,...z;0),n)
973 binomial_coefficient = 1;
978 binomial_coefficient = binomial(numeric(n), numeric(k)) * pow(ex_to<numeric>(a.overall_coeff), numeric(n-k));
981 // Multinomial expansion of power(+(x,...,z;0),k)*c^(n-k):
982 // Iterate over all partitions of k with exactly as many parts as
983 // there are symbolic terms in the basis (including zero parts).
984 partition_with_zero_parts_generator partitions(k, a.seq.size());
986 const std::vector<unsigned>& partition = partitions.get();
987 // All monomials of this partition have the same number of terms and the same coefficient.
988 const unsigned msize = std::count_if(partition.begin(), partition.end(), [](int i) { return i > 0; });
989 const numeric coeff = multinomial_coefficient(partition) * binomial_coefficient;
991 // Iterate over all compositions of the current partition.
992 composition_generator compositions(partition);
994 const std::vector<unsigned>& exponent = compositions.get();
996 monomial.reserve(msize);
997 numeric factor = coeff;
998 for (unsigned i = 0; i < exponent.size(); ++i) {
999 const ex & r = a.seq[i].rest;
1000 GINAC_ASSERT(!is_exactly_a<add>(r));
1001 GINAC_ASSERT(!is_exactly_a<power>(r) ||
1002 !is_exactly_a<numeric>(ex_to<power>(r).exponent) ||
1003 !ex_to<numeric>(ex_to<power>(r).exponent).is_pos_integer() ||
1004 !is_exactly_a<add>(ex_to<power>(r).basis) ||
1005 !is_exactly_a<mul>(ex_to<power>(r).basis) ||
1006 !is_exactly_a<power>(ex_to<power>(r).basis));
1007 GINAC_ASSERT(is_exactly_a<numeric>(a.seq[i].coeff));
1008 const numeric & c = ex_to<numeric>(a.seq[i].coeff);
1009 if (exponent[i] == 0) {
1011 } else if (exponent[i] == 1) {
1013 monomial.push_back(expair(r, _ex1));
1015 factor = factor.mul(c);
1016 } else { // general case exponent[i] > 1
1017 monomial.push_back(expair(r, exponent[i]));
1019 factor = factor.mul(c.power(exponent[i]));
1022 result.push_back(expair(mul(std::move(monomial)).expand(options), factor));
1023 } while (compositions.next());
1024 } while (partitions.next());
1027 GINAC_ASSERT(result.size() == result_size);
1028 if (a.overall_coeff.is_zero()) {
1029 return dynallocate<add>(std::move(result)).setflag(status_flags::expanded);
1031 return dynallocate<add>(std::move(result), ex_to<numeric>(a.overall_coeff).power(n)).setflag(status_flags::expanded);
1036 /** Special case of power::expand_add. Expands a^2 where a is an add.
1037 * @see power::expand_add */
1038 ex power::expand_add_2(const add & a, unsigned options)
1041 size_t result_size = (a.nops() * (a.nops()+1)) / 2;
1042 if (!a.overall_coeff.is_zero()) {
1043 // the result's overall_coeff is one of the terms
1046 result.reserve(result_size);
1048 auto last = a.seq.end();
1050 // power(+(x,...,z;c),2)=power(+(x,...,z;0),2)+2*c*+(x,...,z;0)+c*c
1051 // first part: ignore overall_coeff and expand other terms
1052 for (auto cit0=a.seq.begin(); cit0!=last; ++cit0) {
1053 const ex & r = cit0->rest;
1054 const ex & c = cit0->coeff;
1056 GINAC_ASSERT(!is_exactly_a<add>(r));
1057 GINAC_ASSERT(!is_exactly_a<power>(r) ||
1058 !is_exactly_a<numeric>(ex_to<power>(r).exponent) ||
1059 !ex_to<numeric>(ex_to<power>(r).exponent).is_pos_integer() ||
1060 !is_exactly_a<add>(ex_to<power>(r).basis) ||
1061 !is_exactly_a<mul>(ex_to<power>(r).basis) ||
1062 !is_exactly_a<power>(ex_to<power>(r).basis));
1064 if (c.is_equal(_ex1)) {
1065 if (is_exactly_a<mul>(r)) {
1066 result.push_back(expair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
1069 result.push_back(expair(dynallocate<power>(r, _ex2),
1073 if (is_exactly_a<mul>(r)) {
1074 result.push_back(expair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
1075 ex_to<numeric>(c).power_dyn(*_num2_p)));
1077 result.push_back(expair(dynallocate<power>(r, _ex2),
1078 ex_to<numeric>(c).power_dyn(*_num2_p)));
1082 for (auto cit1=cit0+1; cit1!=last; ++cit1) {
1083 const ex & r1 = cit1->rest;
1084 const ex & c1 = cit1->coeff;
1085 result.push_back(expair(mul(r,r1).expand(options),
1086 _num2_p->mul(ex_to<numeric>(c)).mul_dyn(ex_to<numeric>(c1))));
1090 // second part: add terms coming from overall_coeff (if != 0)
1091 if (!a.overall_coeff.is_zero()) {
1092 for (auto & i : a.seq)
1093 result.push_back(a.combine_pair_with_coeff_to_pair(i, ex_to<numeric>(a.overall_coeff).mul_dyn(*_num2_p)));
1096 GINAC_ASSERT(result.size() == result_size);
1098 if (a.overall_coeff.is_zero()) {
1099 return dynallocate<add>(std::move(result)).setflag(status_flags::expanded);
1101 return dynallocate<add>(std::move(result), ex_to<numeric>(a.overall_coeff).power(2)).setflag(status_flags::expanded);
1105 /** Expand factors of m in m^n where m is a mul and n is an integer.
1106 * @see power::expand */
1107 ex power::expand_mul(const mul & m, const numeric & n, unsigned options, bool from_expand)
1109 GINAC_ASSERT(n.is_integer());
1115 // do not bother to rename indices if there are no any.
1116 if (!(options & expand_options::expand_rename_idx) &&
1117 m.info(info_flags::has_indices))
1118 options |= expand_options::expand_rename_idx;
1119 // Leave it to multiplication since dummy indices have to be renamed
1120 if ((options & expand_options::expand_rename_idx) &&
1121 (get_all_dummy_indices(m).size() > 0) && n.is_positive()) {
1123 exvector va = get_all_dummy_indices(m);
1124 sort(va.begin(), va.end(), ex_is_less());
1126 for (int i=1; i < n.to_int(); i++)
1127 result *= rename_dummy_indices_uniquely(va, m);
1132 distrseq.reserve(m.seq.size());
1133 bool need_reexpand = false;
1135 for (auto & cit : m.seq) {
1136 expair p = m.combine_pair_with_coeff_to_pair(cit, n);
1137 if (from_expand && is_exactly_a<add>(cit.rest) && ex_to<numeric>(p.coeff).is_pos_integer()) {
1138 // this happens when e.g. (a+b)^(1/2) gets squared and
1139 // the resulting product needs to be reexpanded
1140 need_reexpand = true;
1142 distrseq.push_back(p);
1145 const mul & result = dynallocate<mul>(std::move(distrseq), ex_to<numeric>(m.overall_coeff).power_dyn(n));
1147 return ex(result).expand(options);
1149 return result.setflag(status_flags::expanded);
1153 GINAC_BIND_UNARCHIVER(power);
1155 } // namespace GiNaC