3 * Implementation of GiNaC's symbolic exponentiation (basis^exponent). */
6 * GiNaC Copyright (C) 1999 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
28 #include "expairseq.h"
32 #include "relational.h"
37 #ifndef NO_GINAC_NAMESPACE
39 #endif // ndef NO_GINAC_NAMESPACE
41 typedef vector<int> intvector;
44 // default constructor, destructor, copy constructor assignment operator and helpers
49 power::power() : basic(TINFO_power)
51 debugmsg("power default constructor",LOGLEVEL_CONSTRUCT);
56 debugmsg("power destructor",LOGLEVEL_DESTRUCT);
60 power::power(power const & other)
62 debugmsg("power copy constructor",LOGLEVEL_CONSTRUCT);
66 power const & power::operator=(power const & other)
68 debugmsg("power operator=",LOGLEVEL_ASSIGNMENT);
78 void power::copy(power const & other)
82 exponent=other.exponent;
85 void power::destroy(bool call_parent)
87 if (call_parent) basic::destroy(call_parent);
96 power::power(ex const & lh, ex const & rh) : basic(TINFO_power), basis(lh), exponent(rh)
98 debugmsg("power constructor from ex,ex",LOGLEVEL_CONSTRUCT);
99 GINAC_ASSERT(basis.return_type()==return_types::commutative);
102 power::power(ex const & lh, numeric const & rh) : basic(TINFO_power), basis(lh), exponent(rh)
104 debugmsg("power constructor from ex,numeric",LOGLEVEL_CONSTRUCT);
105 GINAC_ASSERT(basis.return_type()==return_types::commutative);
109 // functions overriding virtual functions from bases classes
114 basic * power::duplicate() const
116 debugmsg("power duplicate",LOGLEVEL_DUPLICATE);
117 return new power(*this);
120 void power::print(ostream & os, unsigned upper_precedence) const
122 debugmsg("power print",LOGLEVEL_PRINT);
123 if (precedence<=upper_precedence) os << "(";
124 basis.print(os,precedence);
126 exponent.print(os,precedence);
127 if (precedence<=upper_precedence) os << ")";
130 void power::printraw(ostream & os) const
132 debugmsg("power printraw",LOGLEVEL_PRINT);
137 exponent.printraw(os);
138 os << ",hash=" << hashvalue << ",flags=" << flags << ")";
141 void power::printtree(ostream & os, unsigned indent) const
143 debugmsg("power printtree",LOGLEVEL_PRINT);
145 os << string(indent,' ') << "power: "
146 << "hash=" << hashvalue << " (0x" << hex << hashvalue << dec << ")"
147 << ", flags=" << flags << endl;
148 basis.printtree(os,indent+delta_indent);
149 exponent.printtree(os,indent+delta_indent);
152 static void print_sym_pow(ostream & os, unsigned type, const symbol &x, int exp)
154 // Optimal output of integer powers of symbols to aid compiler CSE
156 x.printcsrc(os, type, 0);
157 } else if (exp == 2) {
158 x.printcsrc(os, type, 0);
160 x.printcsrc(os, type, 0);
161 } else if (exp & 1) {
164 print_sym_pow(os, type, x, exp-1);
167 print_sym_pow(os, type, x, exp >> 1);
169 print_sym_pow(os, type, x, exp >> 1);
174 void power::printcsrc(ostream & os, unsigned type, unsigned upper_precedence) const
176 debugmsg("power print csrc", LOGLEVEL_PRINT);
178 // Integer powers of symbols are printed in a special, optimized way
179 if (exponent.info(info_flags::integer) &&
180 (is_ex_exactly_of_type(basis, symbol) ||
181 is_ex_exactly_of_type(basis, constant))) {
182 int exp = ex_to_numeric(exponent).to_int();
187 if (type == csrc_types::ctype_cl_N)
192 print_sym_pow(os, type, static_cast<const symbol &>(*basis.bp), exp);
195 // <expr>^-1 is printed as "1.0/<expr>" or with the recip() function of CLN
196 } else if (exponent.compare(_num_1()) == 0) {
197 if (type == csrc_types::ctype_cl_N)
201 basis.bp->printcsrc(os, type, 0);
204 // Otherwise, use the pow() or expt() (CLN) functions
206 if (type == csrc_types::ctype_cl_N)
210 basis.bp->printcsrc(os, type, 0);
212 exponent.bp->printcsrc(os, type, 0);
217 bool power::info(unsigned inf) const
219 if (inf==info_flags::polynomial ||
220 inf==info_flags::integer_polynomial ||
221 inf==info_flags::cinteger_polynomial ||
222 inf==info_flags::rational_polynomial ||
223 inf==info_flags::crational_polynomial) {
224 return exponent.info(info_flags::nonnegint);
225 } else if (inf==info_flags::rational_function) {
226 return exponent.info(info_flags::integer);
228 return basic::info(inf);
232 int power::nops() const
237 ex & power::let_op(int const i)
242 return i==0 ? basis : exponent;
245 int power::degree(symbol const & s) const
247 if (is_exactly_of_type(*exponent.bp,numeric)) {
248 if ((*basis.bp).compare(s)==0)
249 return ex_to_numeric(exponent).to_int();
251 return basis.degree(s) * ex_to_numeric(exponent).to_int();
256 int power::ldegree(symbol const & s) const
258 if (is_exactly_of_type(*exponent.bp,numeric)) {
259 if ((*basis.bp).compare(s)==0)
260 return ex_to_numeric(exponent).to_int();
262 return basis.ldegree(s) * ex_to_numeric(exponent).to_int();
267 ex power::coeff(symbol const & s, int const n) const
269 if ((*basis.bp).compare(s)!=0) {
270 // basis not equal to s
276 } else if (is_exactly_of_type(*exponent.bp,numeric)&&
277 (static_cast<numeric const &>(*exponent.bp).compare(numeric(n))==0)) {
284 ex power::eval(int level) const
286 // simplifications: ^(x,0) -> 1 (0^0 handled here)
288 // ^(0,x) -> 0 (except if x is real and negative, in which case an exception is thrown)
290 // ^(c1,c2) -> *(c1^n,c1^(c2-n)) (c1, c2 numeric(), 0<(c2-n)<1 except if c1,c2 are rational, but c1^c2 is not)
291 // ^(^(x,c1),c2) -> ^(x,c1*c2) (c1, c2 numeric(), c2 integer or -1 < c1 <= 1, case c1=1 should not happen, see below!)
292 // ^(*(x,y,z),c1) -> *(x^c1,y^c1,z^c1) (c1 integer)
293 // ^(*(x,c1),c2) -> ^(x,c2)*c1^c2 (c1, c2 numeric(), c1>0)
294 // ^(*(x,c1),c2) -> ^(-x,c2)*c1^c2 (c1, c2 numeric(), c1<0)
296 debugmsg("power eval",LOGLEVEL_MEMBER_FUNCTION);
298 if ((level==1)&&(flags & status_flags::evaluated)) {
300 } else if (level == -max_recursion_level) {
301 throw(std::runtime_error("max recursion level reached"));
304 ex const & ebasis = level==1 ? basis : basis.eval(level-1);
305 ex const & eexponent = level==1 ? exponent : exponent.eval(level-1);
307 bool basis_is_numerical=0;
308 bool exponent_is_numerical=0;
310 numeric * num_exponent;
312 if (is_exactly_of_type(*ebasis.bp,numeric)) {
313 basis_is_numerical=1;
314 num_basis=static_cast<numeric *>(ebasis.bp);
316 if (is_exactly_of_type(*eexponent.bp,numeric)) {
317 exponent_is_numerical=1;
318 num_exponent=static_cast<numeric *>(eexponent.bp);
321 // ^(x,0) -> 1 (0^0 also handled here)
322 if (eexponent.is_zero())
326 if (eexponent.is_equal(_ex1()))
329 // ^(0,x) -> 0 (except if x is real and negative)
330 if (ebasis.is_zero()) {
331 if (exponent_is_numerical && num_exponent->is_negative()) {
332 throw(std::overflow_error("power::eval(): division by zero"));
338 if (ebasis.is_equal(_ex1()))
341 if (basis_is_numerical && exponent_is_numerical) {
342 // ^(c1,c2) -> c1^c2 (c1, c2 numeric(),
343 // except if c1,c2 are rational, but c1^c2 is not)
344 bool basis_is_crational = num_basis->is_crational();
345 bool exponent_is_crational = num_exponent->is_crational();
346 numeric res = (*num_basis).power(*num_exponent);
348 if ((!basis_is_crational || !exponent_is_crational)
349 || res.is_crational()) {
352 GINAC_ASSERT(!num_exponent->is_integer()); // has been handled by now
353 // ^(c1,n/m) -> *(c1^q,c1^(n/m-q)), 0<(n/m-h)<1, q integer
354 if (basis_is_crational && exponent_is_crational
355 && num_exponent->is_real()
356 && !num_exponent->is_integer()) {
358 n = num_exponent->numer();
359 m = num_exponent->denom();
361 if (r.is_negative()) {
365 if (q.is_zero()) // the exponent was in the allowed range 0<(n/m)<1
369 res.push_back(expair(ebasis,r.div(m)));
370 res.push_back(expair(ex(num_basis->power(q)),_ex1()));
371 return (new mul(res))->setflag(status_flags::dynallocated | status_flags::evaluated);
372 /*return mul(num_basis->power(q),
373 power(ex(*num_basis),ex(r.div(m)))).hold();
375 /* return (new mul(num_basis->power(q),
376 power(*num_basis,r.div(m)).hold()))->setflag(status_flags::dynallocated | status_flags::evaluated);
382 // ^(^(x,c1),c2) -> ^(x,c1*c2)
383 // (c1, c2 numeric(), c2 integer or -1 < c1 <= 1,
384 // case c1=1 should not happen, see below!)
385 if (exponent_is_numerical && is_ex_exactly_of_type(ebasis,power)) {
386 power const & sub_power=ex_to_power(ebasis);
387 ex const & sub_basis=sub_power.basis;
388 ex const & sub_exponent=sub_power.exponent;
389 if (is_ex_exactly_of_type(sub_exponent,numeric)) {
390 numeric const & num_sub_exponent=ex_to_numeric(sub_exponent);
391 GINAC_ASSERT(num_sub_exponent!=numeric(1));
392 if (num_exponent->is_integer() || abs(num_sub_exponent)<1) {
393 return power(sub_basis,num_sub_exponent.mul(*num_exponent));
398 // ^(*(x,y,z),c1) -> *(x^c1,y^c1,z^c1) (c1 integer)
399 if (exponent_is_numerical && num_exponent->is_integer() &&
400 is_ex_exactly_of_type(ebasis,mul)) {
401 return expand_mul(ex_to_mul(ebasis), *num_exponent);
404 // ^(*(...,x;c1),c2) -> ^(*(...,x;1),c2)*c1^c2 (c1, c2 numeric(), c1>0)
405 // ^(*(...,x,c1),c2) -> ^(*(...,x;-1),c2)*(-c1)^c2 (c1, c2 numeric(), c1<0)
406 if (exponent_is_numerical && is_ex_exactly_of_type(ebasis,mul)) {
407 GINAC_ASSERT(!num_exponent->is_integer()); // should have been handled above
408 mul const & mulref=ex_to_mul(ebasis);
409 if (!mulref.overall_coeff.is_equal(_ex1())) {
410 numeric const & num_coeff=ex_to_numeric(mulref.overall_coeff);
411 if (num_coeff.is_real()) {
412 if (num_coeff.is_positive()>0) {
413 mul * mulp=new mul(mulref);
414 mulp->overall_coeff=_ex1();
415 mulp->clearflag(status_flags::evaluated);
416 mulp->clearflag(status_flags::hash_calculated);
417 return (new mul(power(*mulp,exponent),
418 power(num_coeff,*num_exponent)))->
419 setflag(status_flags::dynallocated);
421 GINAC_ASSERT(num_coeff.compare(_num0())<0);
422 if (num_coeff.compare(_num_1())!=0) {
423 mul * mulp=new mul(mulref);
424 mulp->overall_coeff=_ex_1();
425 mulp->clearflag(status_flags::evaluated);
426 mulp->clearflag(status_flags::hash_calculated);
427 return (new mul(power(*mulp,exponent),
428 power(abs(num_coeff),*num_exponent)))->
429 setflag(status_flags::dynallocated);
436 if (are_ex_trivially_equal(ebasis,basis) &&
437 are_ex_trivially_equal(eexponent,exponent)) {
440 return (new power(ebasis, eexponent))->setflag(status_flags::dynallocated |
441 status_flags::evaluated);
444 ex power::evalf(int level) const
446 debugmsg("power evalf",LOGLEVEL_MEMBER_FUNCTION);
454 } else if (level == -max_recursion_level) {
455 throw(std::runtime_error("max recursion level reached"));
457 ebasis=basis.evalf(level-1);
458 eexponent=exponent.evalf(level-1);
461 return power(ebasis,eexponent);
464 ex power::subs(lst const & ls, lst const & lr) const
466 ex const & subsed_basis=basis.subs(ls,lr);
467 ex const & subsed_exponent=exponent.subs(ls,lr);
469 if (are_ex_trivially_equal(basis,subsed_basis)&&
470 are_ex_trivially_equal(exponent,subsed_exponent)) {
474 return power(subsed_basis, subsed_exponent);
477 ex power::simplify_ncmul(exvector const & v) const
479 return basic::simplify_ncmul(v);
484 int power::compare_same_type(basic const & other) const
486 GINAC_ASSERT(is_exactly_of_type(other, power));
487 power const & o=static_cast<power const &>(const_cast<basic &>(other));
490 cmpval=basis.compare(o.basis);
492 return exponent.compare(o.exponent);
497 unsigned power::return_type(void) const
499 return basis.return_type();
502 unsigned power::return_type_tinfo(void) const
504 return basis.return_type_tinfo();
507 ex power::expand(unsigned options) const
509 ex expanded_basis=basis.expand(options);
511 if (!is_ex_exactly_of_type(exponent,numeric)||
512 !ex_to_numeric(exponent).is_integer()) {
513 if (are_ex_trivially_equal(basis,expanded_basis)) {
516 return (new power(expanded_basis,exponent))->
517 setflag(status_flags::dynallocated);
521 // integer numeric exponent
522 numeric const & num_exponent=ex_to_numeric(exponent);
523 int int_exponent = num_exponent.to_int();
525 if (int_exponent > 0 && is_ex_exactly_of_type(expanded_basis,add)) {
526 return expand_add(ex_to_add(expanded_basis), int_exponent);
529 if (is_ex_exactly_of_type(expanded_basis,mul)) {
530 return expand_mul(ex_to_mul(expanded_basis), num_exponent);
533 // cannot expand further
534 if (are_ex_trivially_equal(basis,expanded_basis)) {
537 return (new power(expanded_basis,exponent))->
538 setflag(status_flags::dynallocated);
543 // new virtual functions which can be overridden by derived classes
549 // non-virtual functions in this class
552 ex power::expand_add(add const & a, int const n) const
554 // expand a^n where a is an add and n is an integer
557 return expand_add_2(a);
562 sum.reserve((n+1)*(m-1));
564 intvector k_cum(m-1); // k_cum[l]:=sum(i=0,l,k[l]);
565 intvector upper_limit(m-1);
568 for (int l=0; l<m-1; l++) {
577 for (l=0; l<m-1; l++) {
578 ex const & b=a.op(l);
579 GINAC_ASSERT(!is_ex_exactly_of_type(b,add));
580 GINAC_ASSERT(!is_ex_exactly_of_type(b,power)||
581 !is_ex_exactly_of_type(ex_to_power(b).exponent,numeric)||
582 !ex_to_numeric(ex_to_power(b).exponent).is_pos_integer());
583 if (is_ex_exactly_of_type(b,mul)) {
584 term.push_back(expand_mul(ex_to_mul(b),numeric(k[l])));
586 term.push_back(power(b,k[l]));
590 ex const & b=a.op(l);
591 GINAC_ASSERT(!is_ex_exactly_of_type(b,add));
592 GINAC_ASSERT(!is_ex_exactly_of_type(b,power)||
593 !is_ex_exactly_of_type(ex_to_power(b).exponent,numeric)||
594 !ex_to_numeric(ex_to_power(b).exponent).is_pos_integer());
595 if (is_ex_exactly_of_type(b,mul)) {
596 term.push_back(expand_mul(ex_to_mul(b),numeric(n-k_cum[m-2])));
598 term.push_back(power(b,n-k_cum[m-2]));
601 numeric f=binomial(numeric(n),numeric(k[0]));
602 for (l=1; l<m-1; l++) {
603 f=f*binomial(numeric(n-k_cum[l-1]),numeric(k[l]));
608 cout << "begin term" << endl;
609 for (int i=0; i<m-1; i++) {
610 cout << "k[" << i << "]=" << k[i] << endl;
611 cout << "k_cum[" << i << "]=" << k_cum[i] << endl;
612 cout << "upper_limit[" << i << "]=" << upper_limit[i] << endl;
614 for (exvector::const_iterator cit=term.begin(); cit!=term.end(); ++cit) {
615 cout << *cit << endl;
617 cout << "end term" << endl;
620 // TODO: optimize this
621 sum.push_back((new mul(term))->setflag(status_flags::dynallocated));
625 while ((l>=0)&&((++k[l])>upper_limit[l])) {
631 // recalc k_cum[] and upper_limit[]
635 k_cum[l]=k_cum[l-1]+k[l];
637 for (int i=l+1; i<m-1; i++) {
638 k_cum[i]=k_cum[i-1]+k[i];
641 for (int i=l+1; i<m-1; i++) {
642 upper_limit[i]=n-k_cum[i-1];
645 return (new add(sum))->setflag(status_flags::dynallocated);
648 ex power::expand_add_2(add const & a) const
650 // special case: expand a^2 where a is an add
653 unsigned a_nops=a.nops();
654 sum.reserve((a_nops*(a_nops+1))/2);
655 epvector::const_iterator last=a.seq.end();
657 // power(+(x,...,z;c),2)=power(+(x,...,z;0),2)+2*c*+(x,...,z;0)+c*c
658 // first part: ignore overall_coeff and expand other terms
659 for (epvector::const_iterator cit0=a.seq.begin(); cit0!=last; ++cit0) {
660 ex const & r=(*cit0).rest;
661 ex const & c=(*cit0).coeff;
663 GINAC_ASSERT(!is_ex_exactly_of_type(r,add));
664 GINAC_ASSERT(!is_ex_exactly_of_type(r,power)||
665 !is_ex_exactly_of_type(ex_to_power(r).exponent,numeric)||
666 !ex_to_numeric(ex_to_power(r).exponent).is_pos_integer()||
667 !is_ex_exactly_of_type(ex_to_power(r).basis,add)||
668 !is_ex_exactly_of_type(ex_to_power(r).basis,mul)||
669 !is_ex_exactly_of_type(ex_to_power(r).basis,power));
671 if (are_ex_trivially_equal(c,_ex1())) {
672 if (is_ex_exactly_of_type(r,mul)) {
673 sum.push_back(expair(expand_mul(ex_to_mul(r),_num2()),_ex1()));
675 sum.push_back(expair((new power(r,_ex2()))->setflag(status_flags::dynallocated),
679 if (is_ex_exactly_of_type(r,mul)) {
680 sum.push_back(expair(expand_mul(ex_to_mul(r),_num2()),
681 ex_to_numeric(c).power_dyn(_num2())));
683 sum.push_back(expair((new power(r,_ex2()))->setflag(status_flags::dynallocated),
684 ex_to_numeric(c).power_dyn(_num2())));
688 for (epvector::const_iterator cit1=cit0+1; cit1!=last; ++cit1) {
689 ex const & r1=(*cit1).rest;
690 ex const & c1=(*cit1).coeff;
691 sum.push_back(a.combine_ex_with_coeff_to_pair((new mul(r,r1))->setflag(status_flags::dynallocated),
692 _num2().mul(ex_to_numeric(c)).mul_dyn(ex_to_numeric(c1))));
696 GINAC_ASSERT(sum.size()==(a.seq.size()*(a.seq.size()+1))/2);
698 // second part: add terms coming from overall_factor (if != 0)
699 if (!a.overall_coeff.is_equal(_ex0())) {
700 for (epvector::const_iterator cit=a.seq.begin(); cit!=a.seq.end(); ++cit) {
701 sum.push_back(a.combine_pair_with_coeff_to_pair(*cit,ex_to_numeric(a.overall_coeff).mul_dyn(_num2())));
703 sum.push_back(expair(ex_to_numeric(a.overall_coeff).power_dyn(_num2()),_ex1()));
706 GINAC_ASSERT(sum.size()==(a_nops*(a_nops+1))/2);
708 return (new add(sum))->setflag(status_flags::dynallocated);
711 ex power::expand_mul(mul const & m, numeric const & n) const
713 // expand m^n where m is a mul and n is and integer
715 if (n.is_equal(_num0())) {
720 distrseq.reserve(m.seq.size());
721 epvector::const_iterator last=m.seq.end();
722 epvector::const_iterator cit=m.seq.begin();
724 if (is_ex_exactly_of_type((*cit).rest,numeric)) {
725 distrseq.push_back(m.combine_pair_with_coeff_to_pair(*cit,n));
727 // it is safe not to call mul::combine_pair_with_coeff_to_pair()
728 // since n is an integer
729 distrseq.push_back(expair((*cit).rest,
730 ex_to_numeric((*cit).coeff).mul(n)));
734 return (new mul(distrseq,ex_to_numeric(m.overall_coeff).power_dyn(n)))
735 ->setflag(status_flags::dynallocated);
739 ex power::expand_commutative_3(ex const & basis, numeric const & exponent,
740 unsigned options) const
747 add const & addref=static_cast<add const &>(*basis.bp);
751 ex first_operands=add(splitseq);
752 ex last_operand=addref.recombine_pair_to_ex(*(addref.seq.end()-1));
754 int n=exponent.to_int();
755 for (int k=0; k<=n; k++) {
756 distrseq.push_back(binomial(n,k)*power(first_operands,numeric(k))*
757 power(last_operand,numeric(n-k)));
759 return ex((new add(distrseq))->setflag(status_flags::sub_expanded |
760 status_flags::expanded |
761 status_flags::dynallocated )).
767 ex power::expand_noncommutative(ex const & basis, numeric const & exponent,
768 unsigned options) const
770 ex rest_power=ex(power(basis,exponent.add(_num_1()))).
771 expand(options | expand_options::internal_do_not_expand_power_operands);
773 return ex(mul(rest_power,basis),0).
774 expand(options | expand_options::internal_do_not_expand_mul_operands);
779 // static member variables
784 unsigned power::precedence=60;
790 const power some_power;
791 type_info const & typeid_power=typeid(some_power);
795 ex sqrt(ex const & a)
797 return power(a,_ex1_2());
800 #ifndef NO_GINAC_NAMESPACE
802 #endif // ndef NO_GINAC_NAMESPACE