3 * Implementation of GiNaC's symbolic exponentiation (basis^exponent). */
6 * GiNaC Copyright (C) 1999-2007 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"
48 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(power, basic,
49 print_func<print_dflt>(&power::do_print_dflt).
50 print_func<print_latex>(&power::do_print_latex).
51 print_func<print_csrc>(&power::do_print_csrc).
52 print_func<print_python>(&power::do_print_python).
53 print_func<print_python_repr>(&power::do_print_python_repr).
54 print_func<print_csrc_cl_N>(&power::do_print_csrc_cl_N))
56 typedef std::vector<int> intvector;
59 // default constructor
62 power::power() : inherited(&power::tinfo_static) { }
74 power::power(const archive_node &n, lst &sym_lst) : inherited(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);
87 DEFAULT_UNARCHIVE(power)
90 // functions overriding virtual functions from base classes
95 void power::print_power(const print_context & c, const char *powersymbol, const char *openbrace, const char *closebrace, unsigned level) const
97 // Ordinary output of powers using '^' or '**'
98 if (precedence() <= level)
99 c.s << openbrace << '(';
100 basis.print(c, precedence());
103 exponent.print(c, precedence());
105 if (precedence() <= level)
106 c.s << ')' << closebrace;
109 void power::do_print_dflt(const print_dflt & c, unsigned level) const
111 if (exponent.is_equal(_ex1_2)) {
113 // Square roots are printed in a special way
119 print_power(c, "^", "", "", level);
122 void power::do_print_latex(const print_latex & c, unsigned level) const
124 if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_negative()) {
126 // Powers with negative numeric exponents are printed as fractions
128 power(basis, -exponent).eval().print(c);
131 } else if (exponent.is_equal(_ex1_2)) {
133 // Square roots are printed in a special way
139 print_power(c, "^", "{", "}", level);
142 static void print_sym_pow(const print_context & c, const symbol &x, int exp)
144 // Optimal output of integer powers of symbols to aid compiler CSE.
145 // C.f. ISO/IEC 14882:1998, section 1.9 [intro execution], paragraph 15
146 // to learn why such a parenthesation is really necessary.
149 } else if (exp == 2) {
153 } else if (exp & 1) {
156 print_sym_pow(c, x, exp-1);
159 print_sym_pow(c, x, exp >> 1);
161 print_sym_pow(c, x, exp >> 1);
166 void power::do_print_csrc_cl_N(const print_csrc_cl_N& c, unsigned level) const
168 if (exponent.is_equal(_ex_1)) {
181 void power::do_print_csrc(const print_csrc & c, unsigned level) const
183 // Integer powers of symbols are printed in a special, optimized way
184 if (exponent.info(info_flags::integer)
185 && (is_a<symbol>(basis) || is_a<constant>(basis))) {
186 int exp = ex_to<numeric>(exponent).to_int();
193 print_sym_pow(c, ex_to<symbol>(basis), exp);
196 // <expr>^-1 is printed as "1.0/<expr>" or with the recip() function of CLN
197 } else if (exponent.is_equal(_ex_1)) {
202 // Otherwise, use the pow() function
212 void power::do_print_python(const print_python & c, unsigned level) const
214 print_power(c, "**", "", "", level);
217 void power::do_print_python_repr(const print_python_repr & c, unsigned level) const
219 c.s << class_name() << '(';
226 bool power::info(unsigned inf) const
229 case info_flags::polynomial:
230 case info_flags::integer_polynomial:
231 case info_flags::cinteger_polynomial:
232 case info_flags::rational_polynomial:
233 case info_flags::crational_polynomial:
234 return exponent.info(info_flags::nonnegint) &&
236 case info_flags::rational_function:
237 return exponent.info(info_flags::integer) &&
239 case info_flags::algebraic:
240 return !exponent.info(info_flags::integer) ||
242 case info_flags::expanded:
243 return (flags & status_flags::expanded);
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 (new power(mapped_basis, mapped_exponent))->setflag(status_flags::dynallocated);
287 bool power::is_polynomial(const ex & var) const
289 if (exponent.has(var))
291 if (!exponent.info(info_flags::nonnegint))
293 return basis.is_polynomial(var);
296 int power::degree(const ex & s) const
298 if (is_equal(ex_to<basic>(s)))
300 else if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
301 if (basis.is_equal(s))
302 return ex_to<numeric>(exponent).to_int();
304 return basis.degree(s) * ex_to<numeric>(exponent).to_int();
305 } else if (basis.has(s))
306 throw(std::runtime_error("power::degree(): undefined degree because of non-integer exponent"));
311 int power::ldegree(const ex & s) const
313 if (is_equal(ex_to<basic>(s)))
315 else if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
316 if (basis.is_equal(s))
317 return ex_to<numeric>(exponent).to_int();
319 return basis.ldegree(s) * ex_to<numeric>(exponent).to_int();
320 } else if (basis.has(s))
321 throw(std::runtime_error("power::ldegree(): undefined degree because of non-integer exponent"));
326 ex power::coeff(const ex & s, int n) const
328 if (is_equal(ex_to<basic>(s)))
329 return n==1 ? _ex1 : _ex0;
330 else if (!basis.is_equal(s)) {
331 // basis not equal to s
338 if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
340 int int_exp = ex_to<numeric>(exponent).to_int();
346 // non-integer exponents are treated as zero
355 /** Perform automatic term rewriting rules in this class. In the following
356 * x, x1, x2,... stand for a symbolic variables of type ex and c, c1, c2...
357 * stand for such expressions that contain a plain number.
358 * - ^(x,0) -> 1 (also handles ^(0,0))
360 * - ^(0,c) -> 0 or exception (depending on the real part of c)
362 * - ^(c1,c2) -> *(c1^n,c1^(c2-n)) (so that 0<(c2-n)<1, try to evaluate roots, possibly in numerator and denominator of c1)
363 * - ^(^(x,c1),c2) -> ^(x,c1*c2) if x is positive and c1 is real.
364 * - ^(^(x,c1),c2) -> ^(x,c1*c2) (c2 integer or -1 < c1 <= 1, case c1=1 should not happen, see below!)
365 * - ^(*(x,y,z),c) -> *(x^c,y^c,z^c) (if c integer)
366 * - ^(*(x,c1),c2) -> ^(x,c2)*c1^c2 (c1>0)
367 * - ^(*(x,c1),c2) -> ^(-x,c2)*c1^c2 (c1<0)
369 * @param level cut-off in recursive evaluation */
370 ex power::eval(int level) const
372 if ((level==1) && (flags & status_flags::evaluated))
374 else if (level == -max_recursion_level)
375 throw(std::runtime_error("max recursion level reached"));
377 const ex & ebasis = level==1 ? basis : basis.eval(level-1);
378 const ex & eexponent = level==1 ? exponent : exponent.eval(level-1);
380 bool basis_is_numerical = false;
381 bool exponent_is_numerical = false;
382 const numeric *num_basis;
383 const numeric *num_exponent;
385 if (is_exactly_a<numeric>(ebasis)) {
386 basis_is_numerical = true;
387 num_basis = &ex_to<numeric>(ebasis);
389 if (is_exactly_a<numeric>(eexponent)) {
390 exponent_is_numerical = true;
391 num_exponent = &ex_to<numeric>(eexponent);
394 // ^(x,0) -> 1 (0^0 also handled here)
395 if (eexponent.is_zero()) {
396 if (ebasis.is_zero())
397 throw (std::domain_error("power::eval(): pow(0,0) is undefined"));
403 if (eexponent.is_equal(_ex1))
406 // ^(0,c1) -> 0 or exception (depending on real value of c1)
407 if (ebasis.is_zero() && exponent_is_numerical) {
408 if ((num_exponent->real()).is_zero())
409 throw (std::domain_error("power::eval(): pow(0,I) is undefined"));
410 else if ((num_exponent->real()).is_negative())
411 throw (pole_error("power::eval(): division by zero",1));
417 if (ebasis.is_equal(_ex1))
420 // power of a function calculated by separate rules defined for this function
421 if (is_exactly_a<function>(ebasis))
422 return ex_to<function>(ebasis).power(eexponent);
424 // Turn (x^c)^d into x^(c*d) in the case that x is positive and c is real.
425 if (is_exactly_a<power>(ebasis) && ebasis.op(0).info(info_flags::positive) && ebasis.op(1).info(info_flags::real))
426 return power(ebasis.op(0), ebasis.op(1) * eexponent);
428 if (exponent_is_numerical) {
430 // ^(c1,c2) -> c1^c2 (c1, c2 numeric(),
431 // except if c1,c2 are rational, but c1^c2 is not)
432 if (basis_is_numerical) {
433 const bool basis_is_crational = num_basis->is_crational();
434 const bool exponent_is_crational = num_exponent->is_crational();
435 if (!basis_is_crational || !exponent_is_crational) {
436 // return a plain float
437 return (new numeric(num_basis->power(*num_exponent)))->setflag(status_flags::dynallocated |
438 status_flags::evaluated |
439 status_flags::expanded);
442 const numeric res = num_basis->power(*num_exponent);
443 if (res.is_crational()) {
446 GINAC_ASSERT(!num_exponent->is_integer()); // has been handled by now
448 // ^(c1,n/m) -> *(c1^q,c1^(n/m-q)), 0<(n/m-q)<1, q integer
449 if (basis_is_crational && exponent_is_crational
450 && num_exponent->is_real()
451 && !num_exponent->is_integer()) {
452 const numeric n = num_exponent->numer();
453 const numeric m = num_exponent->denom();
455 numeric q = iquo(n, m, r);
456 if (r.is_negative()) {
460 if (q.is_zero()) { // the exponent was in the allowed range 0<(n/m)<1
461 if (num_basis->is_rational() && !num_basis->is_integer()) {
462 // try it for numerator and denominator separately, in order to
463 // partially simplify things like (5/8)^(1/3) -> 1/2*5^(1/3)
464 const numeric bnum = num_basis->numer();
465 const numeric bden = num_basis->denom();
466 const numeric res_bnum = bnum.power(*num_exponent);
467 const numeric res_bden = bden.power(*num_exponent);
468 if (res_bnum.is_integer())
469 return (new mul(power(bden,-*num_exponent),res_bnum))->setflag(status_flags::dynallocated | status_flags::evaluated);
470 if (res_bden.is_integer())
471 return (new mul(power(bnum,*num_exponent),res_bden.inverse()))->setflag(status_flags::dynallocated | status_flags::evaluated);
475 // assemble resulting product, but allowing for a re-evaluation,
476 // because otherwise we'll end up with something like
477 // (7/8)^(4/3) -> 7/8*(1/2*7^(1/3))
478 // instead of 7/16*7^(1/3).
479 ex prod = power(*num_basis,r.div(m));
480 return prod*power(*num_basis,q);
485 // ^(^(x,c1),c2) -> ^(x,c1*c2)
486 // (c1, c2 numeric(), c2 integer or -1 < c1 <= 1,
487 // case c1==1 should not happen, see below!)
488 if (is_exactly_a<power>(ebasis)) {
489 const power & sub_power = ex_to<power>(ebasis);
490 const ex & sub_basis = sub_power.basis;
491 const ex & sub_exponent = sub_power.exponent;
492 if (is_exactly_a<numeric>(sub_exponent)) {
493 const numeric & num_sub_exponent = ex_to<numeric>(sub_exponent);
494 GINAC_ASSERT(num_sub_exponent!=numeric(1));
495 if (num_exponent->is_integer() || (abs(num_sub_exponent) - (*_num1_p)).is_negative()) {
496 return power(sub_basis,num_sub_exponent.mul(*num_exponent));
501 // ^(*(x,y,z),c1) -> *(x^c1,y^c1,z^c1) (c1 integer)
502 if (num_exponent->is_integer() && is_exactly_a<mul>(ebasis)) {
503 return expand_mul(ex_to<mul>(ebasis), *num_exponent, 0);
506 // (2*x + 6*y)^(-4) -> 1/16*(x + 3*y)^(-4)
507 if (num_exponent->is_integer() && is_exactly_a<add>(ebasis)) {
508 numeric icont = ebasis.integer_content();
509 const numeric& lead_coeff =
510 ex_to<numeric>(ex_to<add>(ebasis).seq.begin()->coeff).div_dyn(icont);
512 const bool canonicalizable = lead_coeff.is_integer();
513 const bool unit_normal = lead_coeff.is_pos_integer();
514 if (canonicalizable && (! unit_normal))
515 icont = icont.mul(*_num_1_p);
517 if (canonicalizable && (icont != *_num1_p)) {
518 const add& addref = ex_to<add>(ebasis);
519 add* addp = new add(addref);
520 addp->setflag(status_flags::dynallocated);
521 addp->clearflag(status_flags::hash_calculated);
522 addp->overall_coeff = ex_to<numeric>(addp->overall_coeff).div_dyn(icont);
523 for (epvector::iterator i = addp->seq.begin(); i != addp->seq.end(); ++i)
524 i->coeff = ex_to<numeric>(i->coeff).div_dyn(icont);
526 const numeric c = icont.power(*num_exponent);
527 if (likely(c != *_num1_p))
528 return (new mul(power(*addp, *num_exponent), c))->setflag(status_flags::dynallocated);
530 return power(*addp, *num_exponent);
534 // ^(*(...,x;c1),c2) -> *(^(*(...,x;1),c2),c1^c2) (c1, c2 numeric(), c1>0)
535 // ^(*(...,x;c1),c2) -> *(^(*(...,x;-1),c2),(-c1)^c2) (c1, c2 numeric(), c1<0)
536 if (is_exactly_a<mul>(ebasis)) {
537 GINAC_ASSERT(!num_exponent->is_integer()); // should have been handled above
538 const mul & mulref = ex_to<mul>(ebasis);
539 if (!mulref.overall_coeff.is_equal(_ex1)) {
540 const numeric & num_coeff = ex_to<numeric>(mulref.overall_coeff);
541 if (num_coeff.is_real()) {
542 if (num_coeff.is_positive()) {
543 mul *mulp = new mul(mulref);
544 mulp->overall_coeff = _ex1;
545 mulp->clearflag(status_flags::evaluated);
546 mulp->clearflag(status_flags::hash_calculated);
547 return (new mul(power(*mulp,exponent),
548 power(num_coeff,*num_exponent)))->setflag(status_flags::dynallocated);
550 GINAC_ASSERT(num_coeff.compare(*_num0_p)<0);
551 if (!num_coeff.is_equal(*_num_1_p)) {
552 mul *mulp = new mul(mulref);
553 mulp->overall_coeff = _ex_1;
554 mulp->clearflag(status_flags::evaluated);
555 mulp->clearflag(status_flags::hash_calculated);
556 return (new mul(power(*mulp,exponent),
557 power(abs(num_coeff),*num_exponent)))->setflag(status_flags::dynallocated);
564 // ^(nc,c1) -> ncmul(nc,nc,...) (c1 positive integer, unless nc is a matrix)
565 if (num_exponent->is_pos_integer() &&
566 ebasis.return_type() != return_types::commutative &&
567 !is_a<matrix>(ebasis)) {
568 return ncmul(exvector(num_exponent->to_int(), ebasis), true);
572 if (are_ex_trivially_equal(ebasis,basis) &&
573 are_ex_trivially_equal(eexponent,exponent)) {
576 return (new power(ebasis, eexponent))->setflag(status_flags::dynallocated |
577 status_flags::evaluated);
580 ex power::evalf(int level) const
587 eexponent = exponent;
588 } else if (level == -max_recursion_level) {
589 throw(std::runtime_error("max recursion level reached"));
591 ebasis = basis.evalf(level-1);
592 if (!is_exactly_a<numeric>(exponent))
593 eexponent = exponent.evalf(level-1);
595 eexponent = exponent;
598 return power(ebasis,eexponent);
601 ex power::evalm() const
603 const ex ebasis = basis.evalm();
604 const ex eexponent = exponent.evalm();
605 if (is_a<matrix>(ebasis)) {
606 if (is_exactly_a<numeric>(eexponent)) {
607 return (new matrix(ex_to<matrix>(ebasis).pow(eexponent)))->setflag(status_flags::dynallocated);
610 return (new power(ebasis, eexponent))->setflag(status_flags::dynallocated);
613 bool power::has(const ex & other, unsigned options) const
615 if (!(options & has_options::algebraic))
616 return basic::has(other, options);
617 if (!is_a<power>(other))
618 return basic::has(other, options);
619 if (!exponent.info(info_flags::integer)
620 || !other.op(1).info(info_flags::integer))
621 return basic::has(other, options);
622 if (exponent.info(info_flags::posint)
623 && other.op(1).info(info_flags::posint)
624 && ex_to<numeric>(exponent).to_int()
625 > ex_to<numeric>(other.op(1)).to_int()
626 && basis.match(other.op(0)))
628 if (exponent.info(info_flags::negint)
629 && other.op(1).info(info_flags::negint)
630 && ex_to<numeric>(exponent).to_int()
631 < ex_to<numeric>(other.op(1)).to_int()
632 && basis.match(other.op(0)))
634 return basic::has(other, options);
638 extern bool tryfactsubs(const ex &, const ex &, int &, lst &);
640 ex power::subs(const exmap & m, unsigned options) const
642 const ex &subsed_basis = basis.subs(m, options);
643 const ex &subsed_exponent = exponent.subs(m, options);
645 if (!are_ex_trivially_equal(basis, subsed_basis)
646 || !are_ex_trivially_equal(exponent, subsed_exponent))
647 return power(subsed_basis, subsed_exponent).subs_one_level(m, options);
649 if (!(options & subs_options::algebraic))
650 return subs_one_level(m, options);
652 for (exmap::const_iterator it = m.begin(); it != m.end(); ++it) {
653 int nummatches = std::numeric_limits<int>::max();
655 if (tryfactsubs(*this, it->first, nummatches, repls))
656 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);
659 return subs_one_level(m, options);
662 ex power::eval_ncmul(const exvector & v) const
664 return inherited::eval_ncmul(v);
667 ex power::conjugate() const
669 ex newbasis = basis.conjugate();
670 ex newexponent = exponent.conjugate();
671 if (are_ex_trivially_equal(basis, newbasis) && are_ex_trivially_equal(exponent, newexponent)) {
674 return (new power(newbasis, newexponent))->setflag(status_flags::dynallocated);
677 ex power::real_part() const
679 if (exponent.info(info_flags::integer)) {
680 ex basis_real = basis.real_part();
681 if (basis_real == basis)
683 realsymbol a("a"),b("b");
685 if (exponent.info(info_flags::posint))
686 result = power(a+I*b,exponent);
688 result = power(a/(a*a+b*b)-I*b/(a*a+b*b),-exponent);
689 result = result.expand();
690 result = result.real_part();
691 result = result.subs(lst( a==basis_real, b==basis.imag_part() ));
695 ex a = basis.real_part();
696 ex b = basis.imag_part();
697 ex c = exponent.real_part();
698 ex d = exponent.imag_part();
699 return power(abs(basis),c)*exp(-d*atan2(b,a))*cos(c*atan2(b,a)+d*log(abs(basis)));
702 ex power::imag_part() const
704 if (exponent.info(info_flags::integer)) {
705 ex basis_real = basis.real_part();
706 if (basis_real == basis)
708 realsymbol a("a"),b("b");
710 if (exponent.info(info_flags::posint))
711 result = power(a+I*b,exponent);
713 result = power(a/(a*a+b*b)-I*b/(a*a+b*b),-exponent);
714 result = result.expand();
715 result = result.imag_part();
716 result = result.subs(lst( a==basis_real, b==basis.imag_part() ));
720 ex a=basis.real_part();
721 ex b=basis.imag_part();
722 ex c=exponent.real_part();
723 ex d=exponent.imag_part();
725 power(abs(basis),c)*exp(-d*atan2(b,a))*sin(c*atan2(b,a)+d*log(abs(basis)));
732 /** Implementation of ex::diff() for a power.
734 ex power::derivative(const symbol & s) const
736 if (is_a<numeric>(exponent)) {
737 // D(b^r) = r * b^(r-1) * D(b) (faster than the formula below)
740 newseq.push_back(expair(basis, exponent - _ex1));
741 newseq.push_back(expair(basis.diff(s), _ex1));
742 return mul(newseq, exponent);
744 // D(b^e) = b^e * (D(e)*ln(b) + e*D(b)/b)
746 add(mul(exponent.diff(s), log(basis)),
747 mul(mul(exponent, basis.diff(s)), power(basis, _ex_1))));
751 int power::compare_same_type(const basic & other) const
753 GINAC_ASSERT(is_exactly_a<power>(other));
754 const power &o = static_cast<const power &>(other);
756 int cmpval = basis.compare(o.basis);
760 return exponent.compare(o.exponent);
763 unsigned power::return_type() const
765 return basis.return_type();
768 tinfo_t power::return_type_tinfo() const
770 return basis.return_type_tinfo();
773 ex power::expand(unsigned options) const
775 if (is_a<symbol>(basis) && exponent.info(info_flags::integer))
776 return (new power(*this))->setflag(status_flags::dynallocated | status_flags::expanded);
778 if (options == 0 && (flags & status_flags::expanded))
781 const ex expanded_basis = basis.expand(options);
782 const ex expanded_exponent = exponent.expand(options);
784 // x^(a+b) -> x^a * x^b
785 if (is_exactly_a<add>(expanded_exponent)) {
786 const add &a = ex_to<add>(expanded_exponent);
788 distrseq.reserve(a.seq.size() + 1);
789 epvector::const_iterator last = a.seq.end();
790 epvector::const_iterator cit = a.seq.begin();
792 distrseq.push_back(power(expanded_basis, a.recombine_pair_to_ex(*cit)));
796 // Make sure that e.g. (x+y)^(2+a) expands the (x+y)^2 factor
797 if (ex_to<numeric>(a.overall_coeff).is_integer()) {
798 const numeric &num_exponent = ex_to<numeric>(a.overall_coeff);
799 int int_exponent = num_exponent.to_int();
800 if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
801 distrseq.push_back(expand_add(ex_to<add>(expanded_basis), int_exponent, options));
803 distrseq.push_back(power(expanded_basis, a.overall_coeff));
805 distrseq.push_back(power(expanded_basis, a.overall_coeff));
807 // Make sure that e.g. (x+y)^(1+a) -> x*(x+y)^a + y*(x+y)^a
808 ex r = (new mul(distrseq))->setflag(status_flags::dynallocated);
809 return r.expand(options);
812 if (!is_exactly_a<numeric>(expanded_exponent) ||
813 !ex_to<numeric>(expanded_exponent).is_integer()) {
814 if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent)) {
817 return (new power(expanded_basis,expanded_exponent))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
821 // integer numeric exponent
822 const numeric & num_exponent = ex_to<numeric>(expanded_exponent);
823 int int_exponent = num_exponent.to_int();
826 if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
827 return expand_add(ex_to<add>(expanded_basis), int_exponent, options);
829 // (x*y)^n -> x^n * y^n
830 if (is_exactly_a<mul>(expanded_basis))
831 return expand_mul(ex_to<mul>(expanded_basis), num_exponent, options, true);
833 // cannot expand further
834 if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent))
837 return (new power(expanded_basis,expanded_exponent))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
841 // new virtual functions which can be overridden by derived classes
847 // non-virtual functions in this class
850 /** expand a^n where a is an add and n is a positive integer.
851 * @see power::expand */
852 ex power::expand_add(const add & a, int n, unsigned options) const
855 return expand_add_2(a, options);
857 const size_t m = a.nops();
859 // The number of terms will be the number of combinatorial compositions,
860 // i.e. the number of unordered arrangements of m nonnegative integers
861 // which sum up to n. It is frequently written as C_n(m) and directly
862 // related with binomial coefficients:
863 result.reserve(binomial(numeric(n+m-1), numeric(m-1)).to_int());
865 intvector k_cum(m-1); // k_cum[l]:=sum(i=0,l,k[l]);
866 intvector upper_limit(m-1);
869 for (size_t l=0; l<m-1; ++l) {
878 for (l=0; l<m-1; ++l) {
879 const ex & b = a.op(l);
880 GINAC_ASSERT(!is_exactly_a<add>(b));
881 GINAC_ASSERT(!is_exactly_a<power>(b) ||
882 !is_exactly_a<numeric>(ex_to<power>(b).exponent) ||
883 !ex_to<numeric>(ex_to<power>(b).exponent).is_pos_integer() ||
884 !is_exactly_a<add>(ex_to<power>(b).basis) ||
885 !is_exactly_a<mul>(ex_to<power>(b).basis) ||
886 !is_exactly_a<power>(ex_to<power>(b).basis));
887 if (is_exactly_a<mul>(b))
888 term.push_back(expand_mul(ex_to<mul>(b), numeric(k[l]), options, true));
890 term.push_back(power(b,k[l]));
893 const ex & b = a.op(l);
894 GINAC_ASSERT(!is_exactly_a<add>(b));
895 GINAC_ASSERT(!is_exactly_a<power>(b) ||
896 !is_exactly_a<numeric>(ex_to<power>(b).exponent) ||
897 !ex_to<numeric>(ex_to<power>(b).exponent).is_pos_integer() ||
898 !is_exactly_a<add>(ex_to<power>(b).basis) ||
899 !is_exactly_a<mul>(ex_to<power>(b).basis) ||
900 !is_exactly_a<power>(ex_to<power>(b).basis));
901 if (is_exactly_a<mul>(b))
902 term.push_back(expand_mul(ex_to<mul>(b), numeric(n-k_cum[m-2]), options, true));
904 term.push_back(power(b,n-k_cum[m-2]));
906 numeric f = binomial(numeric(n),numeric(k[0]));
907 for (l=1; l<m-1; ++l)
908 f *= binomial(numeric(n-k_cum[l-1]),numeric(k[l]));
912 result.push_back(ex((new mul(term))->setflag(status_flags::dynallocated)).expand(options));
916 while ((l>=0) && ((++k[l])>upper_limit[l])) {
922 // recalc k_cum[] and upper_limit[]
923 k_cum[l] = (l==0 ? k[0] : k_cum[l-1]+k[l]);
925 for (size_t i=l+1; i<m-1; ++i)
926 k_cum[i] = k_cum[i-1]+k[i];
928 for (size_t i=l+1; i<m-1; ++i)
929 upper_limit[i] = n-k_cum[i-1];
932 return (new add(result))->setflag(status_flags::dynallocated |
933 status_flags::expanded);
937 /** Special case of power::expand_add. Expands a^2 where a is an add.
938 * @see power::expand_add */
939 ex power::expand_add_2(const add & a, unsigned options) const
942 size_t a_nops = a.nops();
943 sum.reserve((a_nops*(a_nops+1))/2);
944 epvector::const_iterator last = a.seq.end();
946 // power(+(x,...,z;c),2)=power(+(x,...,z;0),2)+2*c*+(x,...,z;0)+c*c
947 // first part: ignore overall_coeff and expand other terms
948 for (epvector::const_iterator cit0=a.seq.begin(); cit0!=last; ++cit0) {
949 const ex & r = cit0->rest;
950 const ex & c = cit0->coeff;
952 GINAC_ASSERT(!is_exactly_a<add>(r));
953 GINAC_ASSERT(!is_exactly_a<power>(r) ||
954 !is_exactly_a<numeric>(ex_to<power>(r).exponent) ||
955 !ex_to<numeric>(ex_to<power>(r).exponent).is_pos_integer() ||
956 !is_exactly_a<add>(ex_to<power>(r).basis) ||
957 !is_exactly_a<mul>(ex_to<power>(r).basis) ||
958 !is_exactly_a<power>(ex_to<power>(r).basis));
960 if (c.is_equal(_ex1)) {
961 if (is_exactly_a<mul>(r)) {
962 sum.push_back(expair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
965 sum.push_back(expair((new power(r,_ex2))->setflag(status_flags::dynallocated),
969 if (is_exactly_a<mul>(r)) {
970 sum.push_back(a.combine_ex_with_coeff_to_pair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
971 ex_to<numeric>(c).power_dyn(*_num2_p)));
973 sum.push_back(a.combine_ex_with_coeff_to_pair((new power(r,_ex2))->setflag(status_flags::dynallocated),
974 ex_to<numeric>(c).power_dyn(*_num2_p)));
978 for (epvector::const_iterator cit1=cit0+1; cit1!=last; ++cit1) {
979 const ex & r1 = cit1->rest;
980 const ex & c1 = cit1->coeff;
981 sum.push_back(a.combine_ex_with_coeff_to_pair((new mul(r,r1))->setflag(status_flags::dynallocated),
982 _num2_p->mul(ex_to<numeric>(c)).mul_dyn(ex_to<numeric>(c1))));
986 GINAC_ASSERT(sum.size()==(a.seq.size()*(a.seq.size()+1))/2);
988 // second part: add terms coming from overall_factor (if != 0)
989 if (!a.overall_coeff.is_zero()) {
990 epvector::const_iterator i = a.seq.begin(), end = a.seq.end();
992 sum.push_back(a.combine_pair_with_coeff_to_pair(*i, ex_to<numeric>(a.overall_coeff).mul_dyn(*_num2_p)));
995 sum.push_back(expair(ex_to<numeric>(a.overall_coeff).power_dyn(*_num2_p),_ex1));
998 GINAC_ASSERT(sum.size()==(a_nops*(a_nops+1))/2);
1000 return (new add(sum))->setflag(status_flags::dynallocated | status_flags::expanded);
1003 /** Expand factors of m in m^n where m is a mul and n is an integer.
1004 * @see power::expand */
1005 ex power::expand_mul(const mul & m, const numeric & n, unsigned options, bool from_expand) const
1007 GINAC_ASSERT(n.is_integer());
1013 // Leave it to multiplication since dummy indices have to be renamed
1014 if (get_all_dummy_indices(m).size() > 0 && n.is_positive()) {
1016 exvector va = get_all_dummy_indices(m);
1017 sort(va.begin(), va.end(), ex_is_less());
1019 for (int i=1; i < n.to_int(); i++)
1020 result *= rename_dummy_indices_uniquely(va, m);
1025 distrseq.reserve(m.seq.size());
1026 bool need_reexpand = false;
1028 epvector::const_iterator last = m.seq.end();
1029 epvector::const_iterator cit = m.seq.begin();
1031 expair p = m.combine_pair_with_coeff_to_pair(*cit, n);
1032 if (from_expand && is_exactly_a<add>(cit->rest) && ex_to<numeric>(p.coeff).is_pos_integer()) {
1033 // this happens when e.g. (a+b)^(1/2) gets squared and
1034 // the resulting product needs to be reexpanded
1035 need_reexpand = true;
1037 distrseq.push_back(p);
1041 const mul & result = static_cast<const mul &>((new mul(distrseq, ex_to<numeric>(m.overall_coeff).power_dyn(n)))->setflag(status_flags::dynallocated));
1043 return ex(result).expand(options);
1045 return result.setflag(status_flags::expanded);
1049 } // namespace GiNaC