3 * Implementation of GiNaC's symbolic exponentiation (basis^exponent). */
6 * GiNaC Copyright (C) 1999-2006 Johannes Gutenberg University Mainz, Germany
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29 #include "expairseq.h"
35 #include "operators.h"
36 #include "inifcns.h" // for log() in power::derivative()
43 #include "relational.h"
47 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(power, basic,
48 print_func<print_dflt>(&power::do_print_dflt).
49 print_func<print_latex>(&power::do_print_latex).
50 print_func<print_csrc>(&power::do_print_csrc).
51 print_func<print_python>(&power::do_print_python).
52 print_func<print_python_repr>(&power::do_print_python_repr))
54 typedef std::vector<int> intvector;
57 // default constructor
60 power::power() : inherited(&power::tinfo_static) { }
72 power::power(const archive_node &n, lst &sym_lst) : inherited(n, sym_lst)
74 n.find_ex("basis", basis, sym_lst);
75 n.find_ex("exponent", exponent, sym_lst);
78 void power::archive(archive_node &n) const
80 inherited::archive(n);
81 n.add_ex("basis", basis);
82 n.add_ex("exponent", exponent);
85 DEFAULT_UNARCHIVE(power)
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:1998, 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(const print_csrc & c, unsigned level) const
166 // Integer powers of symbols are printed in a special, optimized way
167 if (exponent.info(info_flags::integer)
168 && (is_a<symbol>(basis) || is_a<constant>(basis))) {
169 int exp = ex_to<numeric>(exponent).to_int();
174 if (is_a<print_csrc_cl_N>(c))
179 print_sym_pow(c, ex_to<symbol>(basis), exp);
182 // <expr>^-1 is printed as "1.0/<expr>" or with the recip() function of CLN
183 } else if (exponent.is_equal(_ex_1)) {
184 if (is_a<print_csrc_cl_N>(c))
191 // Otherwise, use the pow() or expt() (CLN) functions
193 if (is_a<print_csrc_cl_N>(c))
204 void power::do_print_python(const print_python & c, unsigned level) const
206 print_power(c, "**", "", "", level);
209 void power::do_print_python_repr(const print_python_repr & c, unsigned level) const
211 c.s << class_name() << '(';
218 bool power::info(unsigned inf) const
221 case info_flags::polynomial:
222 case info_flags::integer_polynomial:
223 case info_flags::cinteger_polynomial:
224 case info_flags::rational_polynomial:
225 case info_flags::crational_polynomial:
226 return exponent.info(info_flags::nonnegint) &&
228 case info_flags::rational_function:
229 return exponent.info(info_flags::integer) &&
231 case info_flags::algebraic:
232 return !exponent.info(info_flags::integer) ||
235 return inherited::info(inf);
238 size_t power::nops() const
243 ex power::op(size_t i) const
247 return i==0 ? basis : exponent;
250 ex power::map(map_function & f) const
252 const ex &mapped_basis = f(basis);
253 const ex &mapped_exponent = f(exponent);
255 if (!are_ex_trivially_equal(basis, mapped_basis)
256 || !are_ex_trivially_equal(exponent, mapped_exponent))
257 return (new power(mapped_basis, mapped_exponent))->setflag(status_flags::dynallocated);
262 bool power::is_polynomial(const ex & var) const
264 if (exponent.has(var))
266 if (!exponent.info(info_flags::nonnegint))
268 return basis.is_polynomial(var);
271 int power::degree(const ex & s) const
273 if (is_equal(ex_to<basic>(s)))
275 else if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
276 if (basis.is_equal(s))
277 return ex_to<numeric>(exponent).to_int();
279 return basis.degree(s) * ex_to<numeric>(exponent).to_int();
280 } else if (basis.has(s))
281 throw(std::runtime_error("power::degree(): undefined degree because of non-integer exponent"));
286 int power::ldegree(const ex & s) const
288 if (is_equal(ex_to<basic>(s)))
290 else if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
291 if (basis.is_equal(s))
292 return ex_to<numeric>(exponent).to_int();
294 return basis.ldegree(s) * ex_to<numeric>(exponent).to_int();
295 } else if (basis.has(s))
296 throw(std::runtime_error("power::ldegree(): undefined degree because of non-integer exponent"));
301 ex power::coeff(const ex & s, int n) const
303 if (is_equal(ex_to<basic>(s)))
304 return n==1 ? _ex1 : _ex0;
305 else if (!basis.is_equal(s)) {
306 // basis not equal to s
313 if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
315 int int_exp = ex_to<numeric>(exponent).to_int();
321 // non-integer exponents are treated as zero
330 /** Perform automatic term rewriting rules in this class. In the following
331 * x, x1, x2,... stand for a symbolic variables of type ex and c, c1, c2...
332 * stand for such expressions that contain a plain number.
333 * - ^(x,0) -> 1 (also handles ^(0,0))
335 * - ^(0,c) -> 0 or exception (depending on the real part of c)
337 * - ^(c1,c2) -> *(c1^n,c1^(c2-n)) (so that 0<(c2-n)<1, try to evaluate roots, possibly in numerator and denominator of c1)
338 * - ^(^(x,c1),c2) -> ^(x,c1*c2) (c2 integer or -1 < c1 <= 1, case c1=1 should not happen, see below!)
339 * - ^(*(x,y,z),c) -> *(x^c,y^c,z^c) (if c integer)
340 * - ^(*(x,c1),c2) -> ^(x,c2)*c1^c2 (c1>0)
341 * - ^(*(x,c1),c2) -> ^(-x,c2)*c1^c2 (c1<0)
343 * @param level cut-off in recursive evaluation */
344 ex power::eval(int level) const
346 if ((level==1) && (flags & status_flags::evaluated))
348 else if (level == -max_recursion_level)
349 throw(std::runtime_error("max recursion level reached"));
351 const ex & ebasis = level==1 ? basis : basis.eval(level-1);
352 const ex & eexponent = level==1 ? exponent : exponent.eval(level-1);
354 bool basis_is_numerical = false;
355 bool exponent_is_numerical = false;
356 const numeric *num_basis;
357 const numeric *num_exponent;
359 if (is_exactly_a<numeric>(ebasis)) {
360 basis_is_numerical = true;
361 num_basis = &ex_to<numeric>(ebasis);
363 if (is_exactly_a<numeric>(eexponent)) {
364 exponent_is_numerical = true;
365 num_exponent = &ex_to<numeric>(eexponent);
368 // ^(x,0) -> 1 (0^0 also handled here)
369 if (eexponent.is_zero()) {
370 if (ebasis.is_zero())
371 throw (std::domain_error("power::eval(): pow(0,0) is undefined"));
377 if (eexponent.is_equal(_ex1))
380 // ^(0,c1) -> 0 or exception (depending on real value of c1)
381 if (ebasis.is_zero() && exponent_is_numerical) {
382 if ((num_exponent->real()).is_zero())
383 throw (std::domain_error("power::eval(): pow(0,I) is undefined"));
384 else if ((num_exponent->real()).is_negative())
385 throw (pole_error("power::eval(): division by zero",1));
391 if (ebasis.is_equal(_ex1))
394 // power of a function calculated by separate rules defined for this function
395 if (is_exactly_a<function>(ebasis))
396 return ex_to<function>(ebasis).power(eexponent);
398 if (exponent_is_numerical) {
400 // ^(c1,c2) -> c1^c2 (c1, c2 numeric(),
401 // except if c1,c2 are rational, but c1^c2 is not)
402 if (basis_is_numerical) {
403 const bool basis_is_crational = num_basis->is_crational();
404 const bool exponent_is_crational = num_exponent->is_crational();
405 if (!basis_is_crational || !exponent_is_crational) {
406 // return a plain float
407 return (new numeric(num_basis->power(*num_exponent)))->setflag(status_flags::dynallocated |
408 status_flags::evaluated |
409 status_flags::expanded);
412 const numeric res = num_basis->power(*num_exponent);
413 if (res.is_crational()) {
416 GINAC_ASSERT(!num_exponent->is_integer()); // has been handled by now
418 // ^(c1,n/m) -> *(c1^q,c1^(n/m-q)), 0<(n/m-q)<1, q integer
419 if (basis_is_crational && exponent_is_crational
420 && num_exponent->is_real()
421 && !num_exponent->is_integer()) {
422 const numeric n = num_exponent->numer();
423 const numeric m = num_exponent->denom();
425 numeric q = iquo(n, m, r);
426 if (r.is_negative()) {
430 if (q.is_zero()) { // the exponent was in the allowed range 0<(n/m)<1
431 if (num_basis->is_rational() && !num_basis->is_integer()) {
432 // try it for numerator and denominator separately, in order to
433 // partially simplify things like (5/8)^(1/3) -> 1/2*5^(1/3)
434 const numeric bnum = num_basis->numer();
435 const numeric bden = num_basis->denom();
436 const numeric res_bnum = bnum.power(*num_exponent);
437 const numeric res_bden = bden.power(*num_exponent);
438 if (res_bnum.is_integer())
439 return (new mul(power(bden,-*num_exponent),res_bnum))->setflag(status_flags::dynallocated | status_flags::evaluated);
440 if (res_bden.is_integer())
441 return (new mul(power(bnum,*num_exponent),res_bden.inverse()))->setflag(status_flags::dynallocated | status_flags::evaluated);
445 // assemble resulting product, but allowing for a re-evaluation,
446 // because otherwise we'll end up with something like
447 // (7/8)^(4/3) -> 7/8*(1/2*7^(1/3))
448 // instead of 7/16*7^(1/3).
449 ex prod = power(*num_basis,r.div(m));
450 return prod*power(*num_basis,q);
455 // ^(^(x,c1),c2) -> ^(x,c1*c2)
456 // (c1, c2 numeric(), c2 integer or -1 < c1 <= 1,
457 // case c1==1 should not happen, see below!)
458 if (is_exactly_a<power>(ebasis)) {
459 const power & sub_power = ex_to<power>(ebasis);
460 const ex & sub_basis = sub_power.basis;
461 const ex & sub_exponent = sub_power.exponent;
462 if (is_exactly_a<numeric>(sub_exponent)) {
463 const numeric & num_sub_exponent = ex_to<numeric>(sub_exponent);
464 GINAC_ASSERT(num_sub_exponent!=numeric(1));
465 if (num_exponent->is_integer() || (abs(num_sub_exponent) - (*_num1_p)).is_negative())
466 return power(sub_basis,num_sub_exponent.mul(*num_exponent));
470 // ^(*(x,y,z),c1) -> *(x^c1,y^c1,z^c1) (c1 integer)
471 if (num_exponent->is_integer() && is_exactly_a<mul>(ebasis)) {
472 return expand_mul(ex_to<mul>(ebasis), *num_exponent, 0);
475 // ^(*(...,x;c1),c2) -> *(^(*(...,x;1),c2),c1^c2) (c1, c2 numeric(), c1>0)
476 // ^(*(...,x;c1),c2) -> *(^(*(...,x;-1),c2),(-c1)^c2) (c1, c2 numeric(), c1<0)
477 if (is_exactly_a<mul>(ebasis)) {
478 GINAC_ASSERT(!num_exponent->is_integer()); // should have been handled above
479 const mul & mulref = ex_to<mul>(ebasis);
480 if (!mulref.overall_coeff.is_equal(_ex1)) {
481 const numeric & num_coeff = ex_to<numeric>(mulref.overall_coeff);
482 if (num_coeff.is_real()) {
483 if (num_coeff.is_positive()) {
484 mul *mulp = new mul(mulref);
485 mulp->overall_coeff = _ex1;
486 mulp->clearflag(status_flags::evaluated);
487 mulp->clearflag(status_flags::hash_calculated);
488 return (new mul(power(*mulp,exponent),
489 power(num_coeff,*num_exponent)))->setflag(status_flags::dynallocated);
491 GINAC_ASSERT(num_coeff.compare(*_num0_p)<0);
492 if (!num_coeff.is_equal(*_num_1_p)) {
493 mul *mulp = new mul(mulref);
494 mulp->overall_coeff = _ex_1;
495 mulp->clearflag(status_flags::evaluated);
496 mulp->clearflag(status_flags::hash_calculated);
497 return (new mul(power(*mulp,exponent),
498 power(abs(num_coeff),*num_exponent)))->setflag(status_flags::dynallocated);
505 // ^(nc,c1) -> ncmul(nc,nc,...) (c1 positive integer, unless nc is a matrix)
506 if (num_exponent->is_pos_integer() &&
507 ebasis.return_type() != return_types::commutative &&
508 !is_a<matrix>(ebasis)) {
509 return ncmul(exvector(num_exponent->to_int(), ebasis), true);
513 if (are_ex_trivially_equal(ebasis,basis) &&
514 are_ex_trivially_equal(eexponent,exponent)) {
517 return (new power(ebasis, eexponent))->setflag(status_flags::dynallocated |
518 status_flags::evaluated);
521 ex power::evalf(int level) const
528 eexponent = exponent;
529 } else if (level == -max_recursion_level) {
530 throw(std::runtime_error("max recursion level reached"));
532 ebasis = basis.evalf(level-1);
533 if (!is_exactly_a<numeric>(exponent))
534 eexponent = exponent.evalf(level-1);
536 eexponent = exponent;
539 return power(ebasis,eexponent);
542 ex power::evalm() const
544 const ex ebasis = basis.evalm();
545 const ex eexponent = exponent.evalm();
546 if (is_a<matrix>(ebasis)) {
547 if (is_exactly_a<numeric>(eexponent)) {
548 return (new matrix(ex_to<matrix>(ebasis).pow(eexponent)))->setflag(status_flags::dynallocated);
551 return (new power(ebasis, eexponent))->setflag(status_flags::dynallocated);
554 bool power::has(const ex & other, unsigned options) const
556 if (!(options & has_options::algebraic))
557 return basic::has(other, options);
558 if (!is_a<power>(other))
559 return basic::has(other, options);
560 if (!exponent.info(info_flags::integer)
561 || !other.op(1).info(info_flags::integer))
562 return basic::has(other, options);
563 if (exponent.info(info_flags::posint)
564 && other.op(1).info(info_flags::posint)
565 && ex_to<numeric>(exponent).to_int()
566 > ex_to<numeric>(other.op(1)).to_int()
567 && basis.match(other.op(0)))
569 if (exponent.info(info_flags::negint)
570 && other.op(1).info(info_flags::negint)
571 && ex_to<numeric>(exponent).to_int()
572 < ex_to<numeric>(other.op(1)).to_int()
573 && basis.match(other.op(0)))
575 return basic::has(other, options);
579 extern bool tryfactsubs(const ex &, const ex &, int &, lst &);
581 ex power::subs(const exmap & m, unsigned options) const
583 const ex &subsed_basis = basis.subs(m, options);
584 const ex &subsed_exponent = exponent.subs(m, options);
586 if (!are_ex_trivially_equal(basis, subsed_basis)
587 || !are_ex_trivially_equal(exponent, subsed_exponent))
588 return power(subsed_basis, subsed_exponent).subs_one_level(m, options);
590 if (!(options & subs_options::algebraic))
591 return subs_one_level(m, options);
593 for (exmap::const_iterator it = m.begin(); it != m.end(); ++it) {
594 int nummatches = std::numeric_limits<int>::max();
596 if (tryfactsubs(*this, it->first, nummatches, repls))
597 return (ex_to<basic>((*this) * power(it->second.subs(ex(repls), subs_options::no_pattern) / it->first.subs(ex(repls), subs_options::no_pattern), nummatches))).subs_one_level(m, options);
600 return subs_one_level(m, options);
603 ex power::eval_ncmul(const exvector & v) const
605 return inherited::eval_ncmul(v);
608 ex power::conjugate() const
610 ex newbasis = basis.conjugate();
611 ex newexponent = exponent.conjugate();
612 if (are_ex_trivially_equal(basis, newbasis) && are_ex_trivially_equal(exponent, newexponent)) {
615 return (new power(newbasis, newexponent))->setflag(status_flags::dynallocated);
618 ex power::real_part() const
620 if (exponent.info(info_flags::integer)) {
621 ex basis_real = basis.real_part();
622 if (basis_real == basis)
624 realsymbol a("a"),b("b");
626 if (exponent.info(info_flags::posint))
627 result = power(a+I*b,exponent);
629 result = power(a/(a*a+b*b)-I*b/(a*a+b*b),-exponent);
630 result = result.expand();
631 result = result.real_part();
632 result = result.subs(lst( a==basis_real, b==basis.imag_part() ));
636 ex a = basis.real_part();
637 ex b = basis.imag_part();
638 ex c = exponent.real_part();
639 ex d = exponent.imag_part();
640 return power(abs(basis),c)*exp(-d*atan2(b,a))*cos(c*atan2(b,a)+d*log(abs(basis)));
643 ex power::imag_part() const
645 if (exponent.info(info_flags::integer)) {
646 ex basis_real = basis.real_part();
647 if (basis_real == basis)
649 realsymbol a("a"),b("b");
651 if (exponent.info(info_flags::posint))
652 result = power(a+I*b,exponent);
654 result = power(a/(a*a+b*b)-I*b/(a*a+b*b),-exponent);
655 result = result.expand();
656 result = result.imag_part();
657 result = result.subs(lst( a==basis_real, b==basis.imag_part() ));
661 ex a=basis.real_part();
662 ex b=basis.imag_part();
663 ex c=exponent.real_part();
664 ex d=exponent.imag_part();
666 power(abs(basis),c)*exp(-d*atan2(b,a))*sin(c*atan2(b,a)+d*log(abs(basis)));
673 /** Implementation of ex::diff() for a power.
675 ex power::derivative(const symbol & s) const
677 if (is_a<numeric>(exponent)) {
678 // D(b^r) = r * b^(r-1) * D(b) (faster than the formula below)
681 newseq.push_back(expair(basis, exponent - _ex1));
682 newseq.push_back(expair(basis.diff(s), _ex1));
683 return mul(newseq, exponent);
685 // D(b^e) = b^e * (D(e)*ln(b) + e*D(b)/b)
687 add(mul(exponent.diff(s), log(basis)),
688 mul(mul(exponent, basis.diff(s)), power(basis, _ex_1))));
692 int power::compare_same_type(const basic & other) const
694 GINAC_ASSERT(is_exactly_a<power>(other));
695 const power &o = static_cast<const power &>(other);
697 int cmpval = basis.compare(o.basis);
701 return exponent.compare(o.exponent);
704 unsigned power::return_type() const
706 return basis.return_type();
709 tinfo_t power::return_type_tinfo() const
711 return basis.return_type_tinfo();
714 ex power::expand(unsigned options) const
716 if (options == 0 && (flags & status_flags::expanded))
719 const ex expanded_basis = basis.expand(options);
720 const ex expanded_exponent = exponent.expand(options);
722 // x^(a+b) -> x^a * x^b
723 if (is_exactly_a<add>(expanded_exponent)) {
724 const add &a = ex_to<add>(expanded_exponent);
726 distrseq.reserve(a.seq.size() + 1);
727 epvector::const_iterator last = a.seq.end();
728 epvector::const_iterator cit = a.seq.begin();
730 distrseq.push_back(power(expanded_basis, a.recombine_pair_to_ex(*cit)));
734 // Make sure that e.g. (x+y)^(2+a) expands the (x+y)^2 factor
735 if (ex_to<numeric>(a.overall_coeff).is_integer()) {
736 const numeric &num_exponent = ex_to<numeric>(a.overall_coeff);
737 int int_exponent = num_exponent.to_int();
738 if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
739 distrseq.push_back(expand_add(ex_to<add>(expanded_basis), int_exponent, options));
741 distrseq.push_back(power(expanded_basis, a.overall_coeff));
743 distrseq.push_back(power(expanded_basis, a.overall_coeff));
745 // Make sure that e.g. (x+y)^(1+a) -> x*(x+y)^a + y*(x+y)^a
746 ex r = (new mul(distrseq))->setflag(status_flags::dynallocated);
747 return r.expand(options);
750 if (!is_exactly_a<numeric>(expanded_exponent) ||
751 !ex_to<numeric>(expanded_exponent).is_integer()) {
752 if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent)) {
755 return (new power(expanded_basis,expanded_exponent))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
759 // integer numeric exponent
760 const numeric & num_exponent = ex_to<numeric>(expanded_exponent);
761 int int_exponent = num_exponent.to_int();
764 if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
765 return expand_add(ex_to<add>(expanded_basis), int_exponent, options);
767 // (x*y)^n -> x^n * y^n
768 if (is_exactly_a<mul>(expanded_basis))
769 return expand_mul(ex_to<mul>(expanded_basis), num_exponent, options, true);
771 // cannot expand further
772 if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent))
775 return (new power(expanded_basis,expanded_exponent))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
779 // new virtual functions which can be overridden by derived classes
785 // non-virtual functions in this class
788 /** expand a^n where a is an add and n is a positive integer.
789 * @see power::expand */
790 ex power::expand_add(const add & a, int n, unsigned options) const
793 return expand_add_2(a, options);
795 const size_t m = a.nops();
797 // The number of terms will be the number of combinatorial compositions,
798 // i.e. the number of unordered arrangements of m nonnegative integers
799 // which sum up to n. It is frequently written as C_n(m) and directly
800 // related with binomial coefficients:
801 result.reserve(binomial(numeric(n+m-1), numeric(m-1)).to_int());
803 intvector k_cum(m-1); // k_cum[l]:=sum(i=0,l,k[l]);
804 intvector upper_limit(m-1);
807 for (size_t l=0; l<m-1; ++l) {
816 for (l=0; l<m-1; ++l) {
817 const ex & b = a.op(l);
818 GINAC_ASSERT(!is_exactly_a<add>(b));
819 GINAC_ASSERT(!is_exactly_a<power>(b) ||
820 !is_exactly_a<numeric>(ex_to<power>(b).exponent) ||
821 !ex_to<numeric>(ex_to<power>(b).exponent).is_pos_integer() ||
822 !is_exactly_a<add>(ex_to<power>(b).basis) ||
823 !is_exactly_a<mul>(ex_to<power>(b).basis) ||
824 !is_exactly_a<power>(ex_to<power>(b).basis));
825 if (is_exactly_a<mul>(b))
826 term.push_back(expand_mul(ex_to<mul>(b), numeric(k[l]), options, true));
828 term.push_back(power(b,k[l]));
831 const ex & b = a.op(l);
832 GINAC_ASSERT(!is_exactly_a<add>(b));
833 GINAC_ASSERT(!is_exactly_a<power>(b) ||
834 !is_exactly_a<numeric>(ex_to<power>(b).exponent) ||
835 !ex_to<numeric>(ex_to<power>(b).exponent).is_pos_integer() ||
836 !is_exactly_a<add>(ex_to<power>(b).basis) ||
837 !is_exactly_a<mul>(ex_to<power>(b).basis) ||
838 !is_exactly_a<power>(ex_to<power>(b).basis));
839 if (is_exactly_a<mul>(b))
840 term.push_back(expand_mul(ex_to<mul>(b), numeric(n-k_cum[m-2]), options, true));
842 term.push_back(power(b,n-k_cum[m-2]));
844 numeric f = binomial(numeric(n),numeric(k[0]));
845 for (l=1; l<m-1; ++l)
846 f *= binomial(numeric(n-k_cum[l-1]),numeric(k[l]));
850 result.push_back(ex((new mul(term))->setflag(status_flags::dynallocated)).expand(options));
854 while ((l>=0) && ((++k[l])>upper_limit[l])) {
860 // recalc k_cum[] and upper_limit[]
861 k_cum[l] = (l==0 ? k[0] : k_cum[l-1]+k[l]);
863 for (size_t i=l+1; i<m-1; ++i)
864 k_cum[i] = k_cum[i-1]+k[i];
866 for (size_t i=l+1; i<m-1; ++i)
867 upper_limit[i] = n-k_cum[i-1];
870 return (new add(result))->setflag(status_flags::dynallocated |
871 status_flags::expanded);
875 /** Special case of power::expand_add. Expands a^2 where a is an add.
876 * @see power::expand_add */
877 ex power::expand_add_2(const add & a, unsigned options) const
880 size_t a_nops = a.nops();
881 sum.reserve((a_nops*(a_nops+1))/2);
882 epvector::const_iterator last = a.seq.end();
884 // power(+(x,...,z;c),2)=power(+(x,...,z;0),2)+2*c*+(x,...,z;0)+c*c
885 // first part: ignore overall_coeff and expand other terms
886 for (epvector::const_iterator cit0=a.seq.begin(); cit0!=last; ++cit0) {
887 const ex & r = cit0->rest;
888 const ex & c = cit0->coeff;
890 GINAC_ASSERT(!is_exactly_a<add>(r));
891 GINAC_ASSERT(!is_exactly_a<power>(r) ||
892 !is_exactly_a<numeric>(ex_to<power>(r).exponent) ||
893 !ex_to<numeric>(ex_to<power>(r).exponent).is_pos_integer() ||
894 !is_exactly_a<add>(ex_to<power>(r).basis) ||
895 !is_exactly_a<mul>(ex_to<power>(r).basis) ||
896 !is_exactly_a<power>(ex_to<power>(r).basis));
898 if (c.is_equal(_ex1)) {
899 if (is_exactly_a<mul>(r)) {
900 sum.push_back(expair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
903 sum.push_back(expair((new power(r,_ex2))->setflag(status_flags::dynallocated),
907 if (is_exactly_a<mul>(r)) {
908 sum.push_back(a.combine_ex_with_coeff_to_pair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
909 ex_to<numeric>(c).power_dyn(*_num2_p)));
911 sum.push_back(a.combine_ex_with_coeff_to_pair((new power(r,_ex2))->setflag(status_flags::dynallocated),
912 ex_to<numeric>(c).power_dyn(*_num2_p)));
916 for (epvector::const_iterator cit1=cit0+1; cit1!=last; ++cit1) {
917 const ex & r1 = cit1->rest;
918 const ex & c1 = cit1->coeff;
919 sum.push_back(a.combine_ex_with_coeff_to_pair((new mul(r,r1))->setflag(status_flags::dynallocated),
920 _num2_p->mul(ex_to<numeric>(c)).mul_dyn(ex_to<numeric>(c1))));
924 GINAC_ASSERT(sum.size()==(a.seq.size()*(a.seq.size()+1))/2);
926 // second part: add terms coming from overall_factor (if != 0)
927 if (!a.overall_coeff.is_zero()) {
928 epvector::const_iterator i = a.seq.begin(), end = a.seq.end();
930 sum.push_back(a.combine_pair_with_coeff_to_pair(*i, ex_to<numeric>(a.overall_coeff).mul_dyn(*_num2_p)));
933 sum.push_back(expair(ex_to<numeric>(a.overall_coeff).power_dyn(*_num2_p),_ex1));
936 GINAC_ASSERT(sum.size()==(a_nops*(a_nops+1))/2);
938 return (new add(sum))->setflag(status_flags::dynallocated | status_flags::expanded);
941 /** Expand factors of m in m^n where m is a mul and n is and integer.
942 * @see power::expand */
943 ex power::expand_mul(const mul & m, const numeric & n, unsigned options, bool from_expand) const
945 GINAC_ASSERT(n.is_integer());
951 // Leave it to multiplication since dummy indices have to be renamed
952 if (get_all_dummy_indices(m).size() > 0 && n.is_positive()) {
954 exvector va = get_all_dummy_indices(m);
955 sort(va.begin(), va.end(), ex_is_less());
957 for (int i=1; i < n.to_int(); i++)
958 result *= rename_dummy_indices_uniquely(va, m);
963 distrseq.reserve(m.seq.size());
964 bool need_reexpand = false;
966 epvector::const_iterator last = m.seq.end();
967 epvector::const_iterator cit = m.seq.begin();
969 if (is_exactly_a<numeric>(cit->rest)) {
970 distrseq.push_back(m.combine_pair_with_coeff_to_pair(*cit, n));
972 // it is safe not to call mul::combine_pair_with_coeff_to_pair()
973 // since n is an integer
974 numeric new_coeff = ex_to<numeric>(cit->coeff).mul(n);
975 if (from_expand && is_exactly_a<add>(cit->rest) && new_coeff.is_pos_integer()) {
976 // this happens when e.g. (a+b)^(1/2) gets squared and
977 // the resulting product needs to be reexpanded
978 need_reexpand = true;
980 distrseq.push_back(expair(cit->rest, new_coeff));
985 const mul & result = static_cast<const mul &>((new mul(distrseq, ex_to<numeric>(m.overall_coeff).power_dyn(n)))->setflag(status_flags::dynallocated));
987 return ex(result).expand(options);
989 return result.setflag(status_flags::expanded);