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"
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 exponent.info(info_flags::nonnegint) &&
234 case info_flags::rational_function:
235 return exponent.info(info_flags::integer) &&
237 case info_flags::algebraic:
238 return !exponent.info(info_flags::integer) ||
240 case info_flags::expanded:
241 return (flags & status_flags::expanded);
242 case info_flags::positive:
243 return basis.info(info_flags::positive) && exponent.info(info_flags::real);
244 case info_flags::nonnegative:
245 return (basis.info(info_flags::positive) && exponent.info(info_flags::real)) ||
246 (basis.info(info_flags::real) && exponent.info(info_flags::integer) && exponent.info(info_flags::even));
247 case info_flags::has_indices: {
248 if (flags & status_flags::has_indices)
250 else if (flags & status_flags::has_no_indices)
252 else if (basis.info(info_flags::has_indices)) {
253 setflag(status_flags::has_indices);
254 clearflag(status_flags::has_no_indices);
257 clearflag(status_flags::has_indices);
258 setflag(status_flags::has_no_indices);
263 return inherited::info(inf);
266 size_t power::nops() const
271 ex power::op(size_t i) const
275 return i==0 ? basis : exponent;
278 ex power::map(map_function & f) const
280 const ex &mapped_basis = f(basis);
281 const ex &mapped_exponent = f(exponent);
283 if (!are_ex_trivially_equal(basis, mapped_basis)
284 || !are_ex_trivially_equal(exponent, mapped_exponent))
285 return dynallocate<power>(mapped_basis, mapped_exponent);
290 bool power::is_polynomial(const ex & var) const
292 if (basis.is_polynomial(var)) {
294 // basis is non-constant polynomial in var
295 return exponent.info(info_flags::nonnegint);
297 // basis is constant in var
298 return !exponent.has(var);
300 // basis is a non-polynomial function of var
304 int power::degree(const ex & s) const
306 if (is_equal(ex_to<basic>(s)))
308 else if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
309 if (basis.is_equal(s))
310 return ex_to<numeric>(exponent).to_int();
312 return basis.degree(s) * ex_to<numeric>(exponent).to_int();
313 } else if (basis.has(s))
314 throw(std::runtime_error("power::degree(): undefined degree because of non-integer exponent"));
319 int power::ldegree(const ex & s) const
321 if (is_equal(ex_to<basic>(s)))
323 else if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
324 if (basis.is_equal(s))
325 return ex_to<numeric>(exponent).to_int();
327 return basis.ldegree(s) * ex_to<numeric>(exponent).to_int();
328 } else if (basis.has(s))
329 throw(std::runtime_error("power::ldegree(): undefined degree because of non-integer exponent"));
334 ex power::coeff(const ex & s, int n) const
336 if (is_equal(ex_to<basic>(s)))
337 return n==1 ? _ex1 : _ex0;
338 else if (!basis.is_equal(s)) {
339 // basis not equal to s
346 if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
348 int int_exp = ex_to<numeric>(exponent).to_int();
354 // non-integer exponents are treated as zero
363 /** Perform automatic term rewriting rules in this class. In the following
364 * x, x1, x2,... stand for a symbolic variables of type ex and c, c1, c2...
365 * stand for such expressions that contain a plain number.
366 * - ^(x,0) -> 1 (also handles ^(0,0))
368 * - ^(0,c) -> 0 or exception (depending on the real part of c)
370 * - ^(c1,c2) -> *(c1^n,c1^(c2-n)) (so that 0<(c2-n)<1, try to evaluate roots, possibly in numerator and denominator of c1)
371 * - ^(^(x,c1),c2) -> ^(x,c1*c2) if x is positive and c1 is real.
372 * - ^(^(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!)
373 * - ^(*(x,y,z),c) -> *(x^c,y^c,z^c) (if c integer)
374 * - ^(*(x,c1),c2) -> ^(x,c2)*c1^c2 (c1>0)
375 * - ^(*(x,c1),c2) -> ^(-x,c2)*c1^c2 (c1<0)
377 ex power::eval() const
379 if (flags & status_flags::evaluated)
382 const numeric *num_basis = nullptr;
383 const numeric *num_exponent = nullptr;
385 if (is_exactly_a<numeric>(basis)) {
386 num_basis = &ex_to<numeric>(basis);
388 if (is_exactly_a<numeric>(exponent)) {
389 num_exponent = &ex_to<numeric>(exponent);
392 // ^(x,0) -> 1 (0^0 also handled here)
393 if (exponent.is_zero()) {
395 throw (std::domain_error("power::eval(): pow(0,0) is undefined"));
401 if (exponent.is_equal(_ex1))
404 // ^(0,c1) -> 0 or exception (depending on real value of c1)
405 if (basis.is_zero() && num_exponent) {
406 if ((num_exponent->real()).is_zero())
407 throw (std::domain_error("power::eval(): pow(0,I) is undefined"));
408 else if ((num_exponent->real()).is_negative())
409 throw (pole_error("power::eval(): division by zero",1));
415 if (basis.is_equal(_ex1))
418 // power of a function calculated by separate rules defined for this function
419 if (is_exactly_a<function>(basis))
420 return ex_to<function>(basis).power(exponent);
422 // Turn (x^c)^d into x^(c*d) in the case that x is positive and c is real.
423 if (is_exactly_a<power>(basis) && basis.op(0).info(info_flags::positive) && basis.op(1).info(info_flags::real))
424 return power(basis.op(0), basis.op(1) * exponent);
426 if ( num_exponent ) {
428 // ^(c1,c2) -> c1^c2 (c1, c2 numeric(),
429 // except if c1,c2 are rational, but c1^c2 is not)
431 const bool basis_is_crational = num_basis->is_crational();
432 const bool exponent_is_crational = num_exponent->is_crational();
433 if (!basis_is_crational || !exponent_is_crational) {
434 // return a plain float
435 return dynallocate<numeric>(num_basis->power(*num_exponent));
438 const numeric res = num_basis->power(*num_exponent);
439 if (res.is_crational()) {
442 GINAC_ASSERT(!num_exponent->is_integer()); // has been handled by now
444 // ^(c1,n/m) -> *(c1^q,c1^(n/m-q)), 0<(n/m-q)<1, q integer
445 if (basis_is_crational && exponent_is_crational
446 && num_exponent->is_real()
447 && !num_exponent->is_integer()) {
448 const numeric n = num_exponent->numer();
449 const numeric m = num_exponent->denom();
451 numeric q = iquo(n, m, r);
452 if (r.is_negative()) {
456 if (q.is_zero()) { // the exponent was in the allowed range 0<(n/m)<1
457 if (num_basis->is_rational() && !num_basis->is_integer()) {
458 // try it for numerator and denominator separately, in order to
459 // partially simplify things like (5/8)^(1/3) -> 1/2*5^(1/3)
460 const numeric bnum = num_basis->numer();
461 const numeric bden = num_basis->denom();
462 const numeric res_bnum = bnum.power(*num_exponent);
463 const numeric res_bden = bden.power(*num_exponent);
464 if (res_bnum.is_integer())
465 return dynallocate<mul>(dynallocate<power>(bden,-*num_exponent),res_bnum).setflag(status_flags::evaluated);
466 if (res_bden.is_integer())
467 return dynallocate<mul>(dynallocate<power>(bnum,*num_exponent),res_bden.inverse()).setflag(status_flags::evaluated);
471 // assemble resulting product, but allowing for a re-evaluation,
472 // because otherwise we'll end up with something like
473 // (7/8)^(4/3) -> 7/8*(1/2*7^(1/3))
474 // instead of 7/16*7^(1/3).
475 ex prod = power(*num_basis,r.div(m));
476 return prod*power(*num_basis,q);
481 // ^(^(x,c1),c2) -> ^(x,c1*c2)
482 // (c1, c2 numeric(), c2 integer or -1 < c1 <= 1 or (c1=-1 and c2>0),
483 // case c1==1 should not happen, see below!)
484 if (is_exactly_a<power>(basis)) {
485 const power & sub_power = ex_to<power>(basis);
486 const ex & sub_basis = sub_power.basis;
487 const ex & sub_exponent = sub_power.exponent;
488 if (is_exactly_a<numeric>(sub_exponent)) {
489 const numeric & num_sub_exponent = ex_to<numeric>(sub_exponent);
490 GINAC_ASSERT(num_sub_exponent!=numeric(1));
491 if (num_exponent->is_integer() || (abs(num_sub_exponent) - (*_num1_p)).is_negative() ||
492 (num_sub_exponent == *_num_1_p && num_exponent->is_positive())) {
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>(basis)) {
500 return expand_mul(ex_to<mul>(basis), *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>(basis)) {
505 numeric icont = basis.integer_content();
506 const numeric lead_coeff =
507 ex_to<numeric>(ex_to<add>(basis).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>(basis);
516 add & addp = dynallocate<add>(addref);
517 addp.clearflag(status_flags::hash_calculated);
518 addp.overall_coeff = ex_to<numeric>(addp.overall_coeff).div_dyn(icont);
519 for (auto & i : addp.seq)
520 i.coeff = ex_to<numeric>(i.coeff).div_dyn(icont);
522 const numeric c = icont.power(*num_exponent);
523 if (likely(c != *_num1_p))
524 return dynallocate<mul>(dynallocate<power>(addp, *num_exponent), c);
526 return dynallocate<power>(addp, *num_exponent);
530 // ^(*(...,x;c1),c2) -> *(^(*(...,x;1),c2),c1^c2) (c1, c2 numeric(), c1>0)
531 // ^(*(...,x;c1),c2) -> *(^(*(...,x;-1),c2),(-c1)^c2) (c1, c2 numeric(), c1<0)
532 if (is_exactly_a<mul>(basis)) {
533 GINAC_ASSERT(!num_exponent->is_integer()); // should have been handled above
534 const mul & mulref = ex_to<mul>(basis);
535 if (!mulref.overall_coeff.is_equal(_ex1)) {
536 const numeric & num_coeff = ex_to<numeric>(mulref.overall_coeff);
537 if (num_coeff.is_real()) {
538 if (num_coeff.is_positive()) {
539 mul & mulp = dynallocate<mul>(mulref);
540 mulp.overall_coeff = _ex1;
541 mulp.clearflag(status_flags::evaluated | status_flags::hash_calculated);
542 return dynallocate<mul>(dynallocate<power>(mulp, exponent),
543 dynallocate<power>(num_coeff, *num_exponent));
545 GINAC_ASSERT(num_coeff.compare(*_num0_p)<0);
546 if (!num_coeff.is_equal(*_num_1_p)) {
547 mul & mulp = dynallocate<mul>(mulref);
548 mulp.overall_coeff = _ex_1;
549 mulp.clearflag(status_flags::evaluated | status_flags::hash_calculated);
550 return dynallocate<mul>(dynallocate<power>(mulp, exponent),
551 dynallocate<power>(abs(num_coeff), *num_exponent));
558 // ^(nc,c1) -> ncmul(nc,nc,...) (c1 positive integer, unless nc is a matrix)
559 if (num_exponent->is_pos_integer() &&
560 basis.return_type() != return_types::commutative &&
561 !is_a<matrix>(basis)) {
562 return ncmul(exvector(num_exponent->to_int(), basis));
569 ex power::evalf(int level) const
576 eexponent = exponent;
577 } else if (level == -max_recursion_level) {
578 throw(std::runtime_error("max recursion level reached"));
580 ebasis = basis.evalf(level-1);
581 if (!is_exactly_a<numeric>(exponent))
582 eexponent = exponent.evalf(level-1);
584 eexponent = exponent;
587 return power(ebasis,eexponent);
590 ex power::evalm() const
592 const ex ebasis = basis.evalm();
593 const ex eexponent = exponent.evalm();
594 if (is_a<matrix>(ebasis)) {
595 if (is_exactly_a<numeric>(eexponent)) {
596 return dynallocate<matrix>(ex_to<matrix>(ebasis).pow(eexponent));
599 return dynallocate<power>(ebasis, eexponent);
602 bool power::has(const ex & other, unsigned options) const
604 if (!(options & has_options::algebraic))
605 return basic::has(other, options);
606 if (!is_a<power>(other))
607 return basic::has(other, options);
608 if (!exponent.info(info_flags::integer) ||
609 !other.op(1).info(info_flags::integer))
610 return basic::has(other, options);
611 if (exponent.info(info_flags::posint) &&
612 other.op(1).info(info_flags::posint) &&
613 ex_to<numeric>(exponent) > ex_to<numeric>(other.op(1)) &&
614 basis.match(other.op(0)))
616 if (exponent.info(info_flags::negint) &&
617 other.op(1).info(info_flags::negint) &&
618 ex_to<numeric>(exponent) < ex_to<numeric>(other.op(1)) &&
619 basis.match(other.op(0)))
621 return basic::has(other, options);
625 extern bool tryfactsubs(const ex &, const ex &, int &, exmap&);
627 ex power::subs(const exmap & m, unsigned options) const
629 const ex &subsed_basis = basis.subs(m, options);
630 const ex &subsed_exponent = exponent.subs(m, options);
632 if (!are_ex_trivially_equal(basis, subsed_basis)
633 || !are_ex_trivially_equal(exponent, subsed_exponent))
634 return power(subsed_basis, subsed_exponent).subs_one_level(m, options);
636 if (!(options & subs_options::algebraic))
637 return subs_one_level(m, options);
639 for (auto & it : m) {
640 int nummatches = std::numeric_limits<int>::max();
642 if (tryfactsubs(*this, it.first, nummatches, repls)) {
643 ex anum = it.second.subs(repls, subs_options::no_pattern);
644 ex aden = it.first.subs(repls, subs_options::no_pattern);
645 ex result = (*this)*power(anum/aden, nummatches);
646 return (ex_to<basic>(result)).subs_one_level(m, options);
650 return subs_one_level(m, options);
653 ex power::eval_ncmul(const exvector & v) const
655 return inherited::eval_ncmul(v);
658 ex power::conjugate() const
660 // conjugate(pow(x,y))==pow(conjugate(x),conjugate(y)) unless on the
661 // branch cut which runs along the negative real axis.
662 if (basis.info(info_flags::positive)) {
663 ex newexponent = exponent.conjugate();
664 if (are_ex_trivially_equal(exponent, newexponent)) {
667 return dynallocate<power>(basis, newexponent);
669 if (exponent.info(info_flags::integer)) {
670 ex newbasis = basis.conjugate();
671 if (are_ex_trivially_equal(basis, newbasis)) {
674 return dynallocate<power>(newbasis, exponent);
676 return conjugate_function(*this).hold();
679 ex power::real_part() const
681 // basis == a+I*b, exponent == c+I*d
682 const ex a = basis.real_part();
683 const ex c = exponent.real_part();
684 if (basis.is_equal(a) && exponent.is_equal(c)) {
689 const ex b = basis.imag_part();
690 if (exponent.info(info_flags::integer)) {
691 // Re((a+I*b)^c) w/ c ∈ ℤ
692 long N = ex_to<numeric>(c).to_long();
693 // Use real terms in Binomial expansion to construct
694 // Re(expand(power(a+I*b, N))).
695 long NN = N > 0 ? N : -N;
696 ex numer = N > 0 ? _ex1 : power(power(a,2) + power(b,2), NN);
698 for (long n = 0; n <= NN; n += 2) {
699 ex term = binomial(NN, n) * power(a, NN-n) * power(b, n) / numer;
701 result += term; // sign: I^n w/ n == 4*m
703 result -= term; // sign: I^n w/ n == 4*m+2
709 // Re((a+I*b)^(c+I*d))
710 const 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 const ex a = basis.real_part();
717 const ex c = exponent.real_part();
718 if (basis.is_equal(a) && exponent.is_equal(c)) {
723 const ex b = basis.imag_part();
724 if (exponent.info(info_flags::integer)) {
725 // Im((a+I*b)^c) w/ c ∈ ℤ
726 long N = ex_to<numeric>(c).to_long();
727 // Use imaginary terms in Binomial expansion to construct
728 // Im(expand(power(a+I*b, N))).
729 long p = N > 0 ? 1 : 3; // modulus for positive sign
730 long NN = N > 0 ? N : -N;
731 ex numer = N > 0 ? _ex1 : power(power(a,2) + power(b,2), NN);
733 for (long n = 1; n <= NN; n += 2) {
734 ex term = binomial(NN, n) * power(a, NN-n) * power(b, n) / numer;
736 result += term; // sign: I^n w/ n == 4*m+p
738 result -= term; // sign: I^n w/ n == 4*m+2+p
744 // Im((a+I*b)^(c+I*d))
745 const ex d = exponent.imag_part();
746 return power(abs(basis),c)*exp(-d*atan2(b,a))*sin(c*atan2(b,a)+d*log(abs(basis)));
751 /** Implementation of ex::diff() for a power.
753 ex power::derivative(const symbol & s) const
755 if (is_a<numeric>(exponent)) {
756 // D(b^r) = r * b^(r-1) * D(b) (faster than the formula below)
759 newseq.push_back(expair(basis, exponent - _ex1));
760 newseq.push_back(expair(basis.diff(s), _ex1));
761 return mul(std::move(newseq), exponent);
763 // D(b^e) = b^e * (D(e)*ln(b) + e*D(b)/b)
765 add(mul(exponent.diff(s), log(basis)),
766 mul(mul(exponent, basis.diff(s)), power(basis, _ex_1))));
770 int power::compare_same_type(const basic & other) const
772 GINAC_ASSERT(is_exactly_a<power>(other));
773 const power &o = static_cast<const power &>(other);
775 int cmpval = basis.compare(o.basis);
779 return exponent.compare(o.exponent);
782 unsigned power::return_type() const
784 return basis.return_type();
787 return_type_t power::return_type_tinfo() const
789 return basis.return_type_tinfo();
792 ex power::expand(unsigned options) const
794 if (is_a<symbol>(basis) && exponent.info(info_flags::integer)) {
795 // A special case worth optimizing.
796 setflag(status_flags::expanded);
800 // (x*p)^c -> x^c * p^c, if p>0
801 // makes sense before expanding the basis
802 if (is_exactly_a<mul>(basis) && !basis.info(info_flags::indefinite)) {
803 const mul &m = ex_to<mul>(basis);
806 prodseq.reserve(m.seq.size() + 1);
807 powseq.reserve(m.seq.size() + 1);
810 // search for positive/negative factors
811 for (auto & cit : m.seq) {
812 ex e=m.recombine_pair_to_ex(cit);
813 if (e.info(info_flags::positive))
814 prodseq.push_back(pow(e, exponent).expand(options));
815 else if (e.info(info_flags::negative)) {
816 prodseq.push_back(pow(-e, exponent).expand(options));
819 powseq.push_back(cit);
822 // take care on the numeric coefficient
823 ex coeff=(possign? _ex1 : _ex_1);
824 if (m.overall_coeff.info(info_flags::positive) && m.overall_coeff != _ex1)
825 prodseq.push_back(power(m.overall_coeff, exponent));
826 else if (m.overall_coeff.info(info_flags::negative) && m.overall_coeff != _ex_1)
827 prodseq.push_back(power(-m.overall_coeff, exponent));
829 coeff *= m.overall_coeff;
831 // If positive/negative factors are found, then extract them.
832 // In either case we set a flag to avoid the second run on a part
833 // which does not have positive/negative terms.
834 if (prodseq.size() > 0) {
835 ex newbasis = coeff*mul(std::move(powseq));
836 ex_to<basic>(newbasis).setflag(status_flags::purely_indefinite);
837 return dynallocate<mul>(std::move(prodseq)) * pow(newbasis, exponent);
839 ex_to<basic>(basis).setflag(status_flags::purely_indefinite);
842 const ex expanded_basis = basis.expand(options);
843 const ex expanded_exponent = exponent.expand(options);
845 // x^(a+b) -> x^a * x^b
846 if (is_exactly_a<add>(expanded_exponent)) {
847 const add &a = ex_to<add>(expanded_exponent);
849 distrseq.reserve(a.seq.size() + 1);
850 for (auto & cit : a.seq) {
851 distrseq.push_back(power(expanded_basis, a.recombine_pair_to_ex(cit)));
854 // Make sure that e.g. (x+y)^(2+a) expands the (x+y)^2 factor
855 if (ex_to<numeric>(a.overall_coeff).is_integer()) {
856 const numeric &num_exponent = ex_to<numeric>(a.overall_coeff);
857 long int_exponent = num_exponent.to_int();
858 if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
859 distrseq.push_back(expand_add(ex_to<add>(expanded_basis), int_exponent, options));
861 distrseq.push_back(power(expanded_basis, a.overall_coeff));
863 distrseq.push_back(power(expanded_basis, a.overall_coeff));
865 // Make sure that e.g. (x+y)^(1+a) -> x*(x+y)^a + y*(x+y)^a
866 ex r = dynallocate<mul>(distrseq);
867 return r.expand(options);
870 if (!is_exactly_a<numeric>(expanded_exponent) ||
871 !ex_to<numeric>(expanded_exponent).is_integer()) {
872 if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent)) {
875 return dynallocate<power>(expanded_basis, expanded_exponent).setflag(options == 0 ? status_flags::expanded : 0);
879 // integer numeric exponent
880 const numeric & num_exponent = ex_to<numeric>(expanded_exponent);
881 long int_exponent = num_exponent.to_long();
884 if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
885 return expand_add(ex_to<add>(expanded_basis), int_exponent, options);
887 // (x*y)^n -> x^n * y^n
888 if (is_exactly_a<mul>(expanded_basis))
889 return expand_mul(ex_to<mul>(expanded_basis), num_exponent, options, true);
891 // cannot expand further
892 if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent))
895 return dynallocate<power>(expanded_basis, expanded_exponent).setflag(options == 0 ? status_flags::expanded : 0);
899 // new virtual functions which can be overridden by derived classes
905 // non-virtual functions in this class
908 namespace { // anonymous namespace for power::expand_add() helpers
910 /** Helper class to generate all bounded combinatorial partitions of an integer
911 * n with exactly m parts (including zero parts) in non-decreasing order.
913 class partition_generator {
915 // Partitions n into m parts, not including zero parts.
916 // (Cf. OEIS sequence A008284; implementation adapted from Jörg Arndt's
920 // partition: x[1] + x[2] + ... + x[m] = n and sentinel x[0] == 0
924 mpartition2(unsigned n_, unsigned m_)
925 : x(m_+1), n(n_), m(m_)
927 for (int k=1; k<m; ++k)
931 bool next_partition()
933 int u = x[m]; // last element
942 return false; // current is last
953 int m; // number of parts 0<m<=n
954 mutable std::vector<int> partition; // current partition
956 partition_generator(unsigned n_, unsigned m_)
957 : mpgen(n_, 1), m(m_), partition(m_)
959 // returns current partition in non-decreasing order, padded with zeros
960 const std::vector<int>& current() const
962 for (int i = 0; i < m - mpgen.m; ++i)
963 partition[i] = 0; // pad with zeros
965 for (int i = m - mpgen.m; i < m; ++i)
966 partition[i] = mpgen.x[i - m + mpgen.m + 1];
972 if (!mpgen.next_partition()) {
973 if (mpgen.m == m || mpgen.m == mpgen.n)
974 return false; // current is last
975 // increment number of parts
976 mpgen = mpartition2(mpgen.n, mpgen.m + 1);
982 /** Helper class to generate all compositions of a partition of an integer n,
983 * starting with the compositions which has non-decreasing order.
985 class composition_generator {
987 // Generates all distinct permutations of a multiset.
988 // (Based on Aaron Williams' algorithm 1 from "Loopless Generation of
989 // Multiset Permutations using a Constant Number of Variables by Prefix
990 // Shifts." <http://webhome.csc.uvic.ca/~haron/CoolMulti.pdf>)
992 // element of singly linked list
996 element(int val, element* n)
997 : value(val), next(n) {}
999 { // recurses down to the end of the singly linked list
1003 element *head, *i, *after_i;
1004 // NB: Partition must be sorted in non-decreasing order.
1005 explicit coolmulti(const std::vector<int>& partition)
1006 : head(nullptr), i(nullptr), after_i(nullptr)
1008 for (unsigned n = 0; n < partition.size(); ++n) {
1009 head = new element(partition[n], head);
1016 { // deletes singly linked list
1019 void next_permutation()
1022 if (after_i->next != nullptr && i->value >= after_i->next->value)
1026 element *k = before_k->next;
1027 before_k->next = k->next;
1029 if (k->value < head->value)
1034 bool finished() const
1036 return after_i->next == nullptr && after_i->value >= head->value;
1039 bool atend; // needed for simplifying iteration over permutations
1040 bool trivial; // likewise, true if all elements are equal
1041 mutable std::vector<int> composition; // current compositions
1043 explicit composition_generator(const std::vector<int>& partition)
1044 : cmgen(partition), atend(false), trivial(true), composition(partition.size())
1046 for (unsigned i=1; i<partition.size(); ++i)
1047 trivial = trivial && (partition[0] == partition[i]);
1049 const std::vector<int>& current() const
1051 coolmulti::element* it = cmgen.head;
1053 while (it != nullptr) {
1054 composition[i] = it->value;
1062 // This ugly contortion is needed because the original coolmulti
1063 // algorithm requires code duplication of the payload procedure,
1064 // one before the loop and one inside it.
1065 if (trivial || atend)
1067 cmgen.next_permutation();
1068 atend = cmgen.finished();
1073 /** Helper function to compute the multinomial coefficient n!/(p1!*p2!*...*pk!)
1074 * where n = p1+p2+...+pk, i.e. p is a partition of n.
1077 multinomial_coefficient(const std::vector<int> & p)
1079 numeric n = 0, d = 1;
1080 for (auto & it : p) {
1082 d *= factorial(numeric(it));
1084 return factorial(numeric(n)) / d;
1087 } // anonymous namespace
1090 /** expand a^n where a is an add and n is a positive integer.
1091 * @see power::expand */
1092 ex power::expand_add(const add & a, long n, unsigned options)
1094 // The special case power(+(x,...y;x),2) can be optimized better.
1096 return expand_add_2(a, options);
1100 // Consider base as the sum of all symbolic terms and the overall numeric
1101 // coefficient and apply the binomial theorem:
1102 // S = power(+(x,...,z;c),n)
1103 // = power(+(+(x,...,z;0);c),n)
1104 // = sum(binomial(n,k)*power(+(x,...,z;0),k)*c^(n-k), k=1..n) + c^n
1105 // Then, apply the multinomial theorem to expand all power(+(x,...,z;0),k):
1106 // The multinomial theorem is computed by an outer loop over all
1107 // partitions of the exponent and an inner loop over all compositions of
1108 // that partition. This method makes the expansion a combinatorial
1109 // problem and allows us to directly construct the expanded sum and also
1110 // to re-use the multinomial coefficients (since they depend only on the
1111 // partition, not on the composition).
1113 // multinomial power(+(x,y,z;0),3) example:
1114 // partition : compositions : multinomial coefficient
1115 // [0,0,3] : [3,0,0],[0,3,0],[0,0,3] : 3!/(3!*0!*0!) = 1
1116 // [0,1,2] : [2,1,0],[1,2,0],[2,0,1],... : 3!/(2!*1!*0!) = 3
1117 // [1,1,1] : [1,1,1] : 3!/(1!*1!*1!) = 6
1118 // => (x + y + z)^3 =
1120 // + 3*x^2*y + 3*x*y^2 + 3*y^2*z + 3*y*z^2 + 3*x*z^2 + 3*x^2*z
1123 // multinomial power(+(x,y,z;0),4) example:
1124 // partition : compositions : multinomial coefficient
1125 // [0,0,4] : [4,0,0],[0,4,0],[0,0,4] : 4!/(4!*0!*0!) = 1
1126 // [0,1,3] : [3,1,0],[1,3,0],[3,0,1],... : 4!/(3!*1!*0!) = 4
1127 // [0,2,2] : [2,2,0],[2,0,2],[0,2,2] : 4!/(2!*2!*0!) = 6
1128 // [1,1,2] : [2,1,1],[1,2,1],[1,1,2] : 4!/(2!*1!*1!) = 12
1129 // (no [1,1,1,1] partition since it has too many parts)
1130 // => (x + y + z)^4 =
1132 // + 4*x^3*y + 4*x*y^3 + 4*y^3*z + 4*y*z^3 + 4*x*z^3 + 4*x^3*z
1133 // + 6*x^2*y^2 + 6*y^2*z^2 + 6*x^2*z^2
1134 // + 12*x^2*y*z + 12*x*y^2*z + 12*x*y*z^2
1138 // for k from 0 to n:
1139 // f = c^(n-k)*binomial(n,k)
1140 // for p in all partitions of n with m parts (including zero parts):
1141 // h = f * multinomial coefficient of p
1142 // for c in all compositions of p:
1144 // for e in all elements of c:
1150 // The number of terms will be the number of combinatorial compositions,
1151 // i.e. the number of unordered arrangements of m nonnegative integers
1152 // which sum up to n. It is frequently written as C_n(m) and directly
1153 // related with binomial coefficients: binomial(n+m-1,m-1).
1154 size_t result_size = binomial(numeric(n+a.nops()-1), numeric(a.nops()-1)).to_long();
1155 if (!a.overall_coeff.is_zero()) {
1156 // the result's overall_coeff is one of the terms
1159 result.reserve(result_size);
1161 // Iterate over all terms in binomial expansion of
1162 // S = power(+(x,...,z;c),n)
1163 // = sum(binomial(n,k)*power(+(x,...,z;0),k)*c^(n-k), k=1..n) + c^n
1164 for (int k = 1; k <= n; ++k) {
1165 numeric binomial_coefficient; // binomial(n,k)*c^(n-k)
1166 if (a.overall_coeff.is_zero()) {
1167 // degenerate case with zero overall_coeff:
1168 // apply multinomial theorem directly to power(+(x,...z;0),n)
1169 binomial_coefficient = 1;
1174 binomial_coefficient = binomial(numeric(n), numeric(k)) * pow(ex_to<numeric>(a.overall_coeff), numeric(n-k));
1177 // Multinomial expansion of power(+(x,...,z;0),k)*c^(n-k):
1178 // Iterate over all partitions of k with exactly as many parts as
1179 // there are symbolic terms in the basis (including zero parts).
1180 partition_generator partitions(k, a.seq.size());
1182 const std::vector<int>& partition = partitions.current();
1183 // All monomials of this partition have the same number of terms and the same coefficient.
1184 const unsigned msize = std::count_if(partition.begin(), partition.end(), [](int i) { return i > 0; });
1185 const numeric coeff = multinomial_coefficient(partition) * binomial_coefficient;
1187 // Iterate over all compositions of the current partition.
1188 composition_generator compositions(partition);
1190 const std::vector<int>& exponent = compositions.current();
1192 monomial.reserve(msize);
1193 numeric factor = coeff;
1194 for (unsigned i = 0; i < exponent.size(); ++i) {
1195 const ex & r = a.seq[i].rest;
1196 GINAC_ASSERT(!is_exactly_a<add>(r));
1197 GINAC_ASSERT(!is_exactly_a<power>(r) ||
1198 !is_exactly_a<numeric>(ex_to<power>(r).exponent) ||
1199 !ex_to<numeric>(ex_to<power>(r).exponent).is_pos_integer() ||
1200 !is_exactly_a<add>(ex_to<power>(r).basis) ||
1201 !is_exactly_a<mul>(ex_to<power>(r).basis) ||
1202 !is_exactly_a<power>(ex_to<power>(r).basis));
1203 GINAC_ASSERT(is_exactly_a<numeric>(a.seq[i].coeff));
1204 const numeric & c = ex_to<numeric>(a.seq[i].coeff);
1205 if (exponent[i] == 0) {
1207 } else if (exponent[i] == 1) {
1209 monomial.push_back(expair(r, _ex1));
1211 factor = factor.mul(c);
1212 } else { // general case exponent[i] > 1
1213 monomial.push_back(expair(r, exponent[i]));
1215 factor = factor.mul(c.power(exponent[i]));
1218 result.push_back(expair(mul(monomial).expand(options), factor));
1219 } while (compositions.next());
1220 } while (partitions.next());
1223 GINAC_ASSERT(result.size() == result_size);
1224 if (a.overall_coeff.is_zero()) {
1225 return dynallocate<add>(std::move(result)).setflag(status_flags::expanded);
1227 return dynallocate<add>(std::move(result), ex_to<numeric>(a.overall_coeff).power(n)).setflag(status_flags::expanded);
1232 /** Special case of power::expand_add. Expands a^2 where a is an add.
1233 * @see power::expand_add */
1234 ex power::expand_add_2(const add & a, unsigned options)
1237 size_t result_size = (a.nops() * (a.nops()+1)) / 2;
1238 if (!a.overall_coeff.is_zero()) {
1239 // the result's overall_coeff is one of the terms
1242 result.reserve(result_size);
1244 epvector::const_iterator last = a.seq.end();
1246 // power(+(x,...,z;c),2)=power(+(x,...,z;0),2)+2*c*+(x,...,z;0)+c*c
1247 // first part: ignore overall_coeff and expand other terms
1248 for (epvector::const_iterator cit0=a.seq.begin(); cit0!=last; ++cit0) {
1249 const ex & r = cit0->rest;
1250 const ex & c = cit0->coeff;
1252 GINAC_ASSERT(!is_exactly_a<add>(r));
1253 GINAC_ASSERT(!is_exactly_a<power>(r) ||
1254 !is_exactly_a<numeric>(ex_to<power>(r).exponent) ||
1255 !ex_to<numeric>(ex_to<power>(r).exponent).is_pos_integer() ||
1256 !is_exactly_a<add>(ex_to<power>(r).basis) ||
1257 !is_exactly_a<mul>(ex_to<power>(r).basis) ||
1258 !is_exactly_a<power>(ex_to<power>(r).basis));
1260 if (c.is_equal(_ex1)) {
1261 if (is_exactly_a<mul>(r)) {
1262 result.push_back(expair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
1265 result.push_back(expair(dynallocate<power>(r, _ex2),
1269 if (is_exactly_a<mul>(r)) {
1270 result.push_back(expair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
1271 ex_to<numeric>(c).power_dyn(*_num2_p)));
1273 result.push_back(expair(dynallocate<power>(r, _ex2),
1274 ex_to<numeric>(c).power_dyn(*_num2_p)));
1278 for (epvector::const_iterator cit1=cit0+1; cit1!=last; ++cit1) {
1279 const ex & r1 = cit1->rest;
1280 const ex & c1 = cit1->coeff;
1281 result.push_back(expair(mul(r,r1).expand(options),
1282 _num2_p->mul(ex_to<numeric>(c)).mul_dyn(ex_to<numeric>(c1))));
1286 // second part: add terms coming from overall_coeff (if != 0)
1287 if (!a.overall_coeff.is_zero()) {
1288 for (auto & i : a.seq)
1289 result.push_back(a.combine_pair_with_coeff_to_pair(i, ex_to<numeric>(a.overall_coeff).mul_dyn(*_num2_p)));
1292 GINAC_ASSERT(result.size() == result_size);
1294 if (a.overall_coeff.is_zero()) {
1295 return dynallocate<add>(std::move(result)).setflag(status_flags::expanded);
1297 return dynallocate<add>(std::move(result), ex_to<numeric>(a.overall_coeff).power(2)).setflag(status_flags::expanded);
1301 /** Expand factors of m in m^n where m is a mul and n is an integer.
1302 * @see power::expand */
1303 ex power::expand_mul(const mul & m, const numeric & n, unsigned options, bool from_expand)
1305 GINAC_ASSERT(n.is_integer());
1311 // do not bother to rename indices if there are no any.
1312 if (!(options & expand_options::expand_rename_idx) &&
1313 m.info(info_flags::has_indices))
1314 options |= expand_options::expand_rename_idx;
1315 // Leave it to multiplication since dummy indices have to be renamed
1316 if ((options & expand_options::expand_rename_idx) &&
1317 (get_all_dummy_indices(m).size() > 0) && n.is_positive()) {
1319 exvector va = get_all_dummy_indices(m);
1320 sort(va.begin(), va.end(), ex_is_less());
1322 for (int i=1; i < n.to_int(); i++)
1323 result *= rename_dummy_indices_uniquely(va, m);
1328 distrseq.reserve(m.seq.size());
1329 bool need_reexpand = false;
1331 for (auto & cit : m.seq) {
1332 expair p = m.combine_pair_with_coeff_to_pair(cit, n);
1333 if (from_expand && is_exactly_a<add>(cit.rest) && ex_to<numeric>(p.coeff).is_pos_integer()) {
1334 // this happens when e.g. (a+b)^(1/2) gets squared and
1335 // the resulting product needs to be reexpanded
1336 need_reexpand = true;
1338 distrseq.push_back(p);
1341 const mul & result = dynallocate<mul>(std::move(distrseq), ex_to<numeric>(m.overall_coeff).power_dyn(n));
1343 return ex(result).expand(options);
1345 return result.setflag(status_flags::expanded);
1349 GINAC_BIND_UNARCHIVER(power);
1351 } // namespace GiNaC