]> www.ginac.de Git - ginac.git/blob - ginac/power.cpp
- introduced info_flags::cinteger, info_flags::crational,
[ginac.git] / ginac / power.cpp
1 /** @file power.cpp
2  *
3  *  Implementation of GiNaC's symbolic exponentiation (basis^exponent). */
4
5 /*
6  *  GiNaC Copyright (C) 1999 Johannes Gutenberg University Mainz, Germany
7  *
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.
12  *
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.
17  *
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
21  */
22
23 #include <vector>
24 #include <iostream>
25 #include <stdexcept>
26
27 #include "power.h"
28 #include "expairseq.h"
29 #include "add.h"
30 #include "mul.h"
31 #include "numeric.h"
32 #include "relational.h"
33 #include "symbol.h"
34 #include "debugmsg.h"
35
36 #ifndef NO_GINAC_NAMESPACE
37 namespace GiNaC {
38 #endif // ndef NO_GINAC_NAMESPACE
39
40 typedef vector<int> intvector;
41
42 //////////
43 // default constructor, destructor, copy constructor assignment operator and helpers
44 //////////
45
46 // public
47
48 power::power() : basic(TINFO_power)
49 {
50     debugmsg("power default constructor",LOGLEVEL_CONSTRUCT);
51 }
52
53 power::~power()
54 {
55     debugmsg("power destructor",LOGLEVEL_DESTRUCT);
56     destroy(0);
57 }
58
59 power::power(power const & other)
60 {
61     debugmsg("power copy constructor",LOGLEVEL_CONSTRUCT);
62     copy(other);
63 }
64
65 power const & power::operator=(power const & other)
66 {
67     debugmsg("power operator=",LOGLEVEL_ASSIGNMENT);
68     if (this != &other) {
69         destroy(1);
70         copy(other);
71     }
72     return *this;
73 }
74
75 // protected
76
77 void power::copy(power const & other)
78 {
79     basic::copy(other);
80     basis=other.basis;
81     exponent=other.exponent;
82 }
83
84 void power::destroy(bool call_parent)
85 {
86     if (call_parent) basic::destroy(call_parent);
87 }
88
89 //////////
90 // other constructors
91 //////////
92
93 // public
94
95 power::power(ex const & lh, ex const & rh) : basic(TINFO_power), basis(lh), exponent(rh)
96 {
97     debugmsg("power constructor from ex,ex",LOGLEVEL_CONSTRUCT);
98     GINAC_ASSERT(basis.return_type()==return_types::commutative);
99 }
100
101 power::power(ex const & lh, numeric const & rh) : basic(TINFO_power), basis(lh), exponent(rh)
102 {
103     debugmsg("power constructor from ex,numeric",LOGLEVEL_CONSTRUCT);
104     GINAC_ASSERT(basis.return_type()==return_types::commutative);
105 }
106
107 //////////
108 // functions overriding virtual functions from bases classes
109 //////////
110
111 // public
112
113 basic * power::duplicate() const
114 {
115     debugmsg("power duplicate",LOGLEVEL_DUPLICATE);
116     return new power(*this);
117 }
118
119 void power::print(ostream & os, unsigned upper_precedence) const
120 {
121     debugmsg("power print",LOGLEVEL_PRINT);
122     if (precedence<=upper_precedence) os << "(";
123     basis.print(os,precedence);
124     os << "^";
125     exponent.print(os,precedence);
126     if (precedence<=upper_precedence) os << ")";
127 }
128
129 void power::printraw(ostream & os) const
130 {
131     debugmsg("power printraw",LOGLEVEL_PRINT);
132
133     os << "power(";
134     basis.printraw(os);
135     os << ",";
136     exponent.printraw(os);
137     os << ",hash=" << hashvalue << ",flags=" << flags << ")";
138 }
139
140 void power::printtree(ostream & os, unsigned indent) const
141 {
142     debugmsg("power printtree",LOGLEVEL_PRINT);
143
144     os << string(indent,' ') << "power: "
145        << "hash=" << hashvalue << " (0x" << hex << hashvalue << dec << ")"
146        << ", flags=" << flags << endl;
147     basis.printtree(os,indent+delta_indent);
148     exponent.printtree(os,indent+delta_indent);
149 }
150
151 static void print_sym_pow(ostream & os, unsigned type, const symbol &x, int exp)
152 {
153     // Optimal output of integer powers of symbols to aid compiler CSE
154     if (exp == 1) {
155         x.printcsrc(os, type, 0);
156     } else if (exp == 2) {
157         x.printcsrc(os, type, 0);
158         os << "*";
159         x.printcsrc(os, type, 0);
160     } else if (exp & 1) {
161         x.printcsrc(os, 0);
162         os << "*";
163         print_sym_pow(os, type, x, exp-1);
164     } else {
165         os << "(";
166         print_sym_pow(os, type, x, exp >> 1);
167         os << ")*(";
168         print_sym_pow(os, type, x, exp >> 1);
169         os << ")";
170     }
171 }
172
173 void power::printcsrc(ostream & os, unsigned type, unsigned upper_precedence) const
174 {
175     debugmsg("power print csrc", LOGLEVEL_PRINT);
176     
177     // Integer powers of symbols are printed in a special, optimized way
178     if (exponent.info(info_flags::integer) &&
179         (is_ex_exactly_of_type(basis, symbol) ||
180          is_ex_exactly_of_type(basis, constant))) {
181         int exp = ex_to_numeric(exponent).to_int();
182         if (exp > 0)
183             os << "(";
184         else {
185             exp = -exp;
186             if (type == csrc_types::ctype_cl_N)
187                 os << "recip(";
188             else
189                 os << "1.0/(";
190         }
191         print_sym_pow(os, type, static_cast<const symbol &>(*basis.bp), exp);
192         os << ")";
193
194     // <expr>^-1 is printed as "1.0/<expr>" or with the recip() function of CLN
195     } else if (exponent.compare(numMINUSONE()) == 0) {
196         if (type == csrc_types::ctype_cl_N)
197             os << "recip(";
198         else
199             os << "1.0/(";
200         basis.bp->printcsrc(os, type, 0);
201         os << ")";
202
203     // Otherwise, use the pow() or expt() (CLN) functions
204     } else {
205         if (type == csrc_types::ctype_cl_N)
206             os << "expt(";
207         else
208             os << "pow(";
209         basis.bp->printcsrc(os, type, 0);
210         os << ",";
211         exponent.bp->printcsrc(os, type, 0);
212         os << ")";
213     }
214 }
215
216 bool power::info(unsigned inf) const
217 {
218     if (inf==info_flags::polynomial ||
219         inf==info_flags::integer_polynomial ||
220         inf==info_flags::cinteger_polynomial ||
221         inf==info_flags::rational_polynomial ||
222         inf==info_flags::crational_polynomial) {
223         return exponent.info(info_flags::nonnegint);
224     } else if (inf==info_flags::rational_function) {
225         return exponent.info(info_flags::integer);
226     } else {
227         return basic::info(inf);
228     }
229 }
230
231 int power::nops() const
232 {
233     return 2;
234 }
235
236 ex & power::let_op(int const i)
237 {
238     GINAC_ASSERT(i>=0);
239     GINAC_ASSERT(i<2);
240
241     return i==0 ? basis : exponent;
242 }
243
244 int power::degree(symbol const & s) const
245 {
246     if (is_exactly_of_type(*exponent.bp,numeric)) {
247         if ((*basis.bp).compare(s)==0)
248             return ex_to_numeric(exponent).to_int();
249         else
250             return basis.degree(s) * ex_to_numeric(exponent).to_int();
251     }
252     return 0;
253 }
254
255 int power::ldegree(symbol const & s) const 
256 {
257     if (is_exactly_of_type(*exponent.bp,numeric)) {
258         if ((*basis.bp).compare(s)==0)
259             return ex_to_numeric(exponent).to_int();
260         else
261             return basis.ldegree(s) * ex_to_numeric(exponent).to_int();
262     }
263     return 0;
264 }
265
266 ex power::coeff(symbol const & s, int const n) const
267 {
268     if ((*basis.bp).compare(s)!=0) {
269         // basis not equal to s
270         if (n==0) {
271             return *this;
272         } else {
273             return exZERO();
274         }
275     } else if (is_exactly_of_type(*exponent.bp,numeric)&&
276                (static_cast<numeric const &>(*exponent.bp).compare(numeric(n))==0)) {
277         return exONE();
278     }
279
280     return exZERO();
281 }
282
283 ex power::eval(int level) const
284 {
285     // simplifications: ^(x,0) -> 1 (0^0 handled here)
286     //                  ^(x,1) -> x
287     //                  ^(0,x) -> 0 (except if x is real and negative, in which case an exception is thrown)
288     //                  ^(1,x) -> 1
289     //                  ^(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)
290     //                  ^(^(x,c1),c2) -> ^(x,c1*c2) (c1, c2 numeric(), c2 integer or -1 < c1 <= 1, case c1=1 should not happen, see below!)
291     //                  ^(*(x,y,z),c1) -> *(x^c1,y^c1,z^c1) (c1 integer)
292     //                  ^(*(x,c1),c2) -> ^(x,c2)*c1^c2 (c1, c2 numeric(), c1>0)
293     //                  ^(*(x,c1),c2) -> ^(-x,c2)*c1^c2 (c1, c2 numeric(), c1<0)
294     
295     debugmsg("power eval",LOGLEVEL_MEMBER_FUNCTION);
296
297     if ((level==1)&&(flags & status_flags::evaluated)) {
298         return *this;
299     } else if (level == -max_recursion_level) {
300         throw(std::runtime_error("max recursion level reached"));
301     }
302     
303     ex const & ebasis    = level==1 ? basis    : basis.eval(level-1);
304     ex const & eexponent = level==1 ? exponent : exponent.eval(level-1);
305
306     bool basis_is_numerical=0;
307     bool exponent_is_numerical=0;
308     numeric * num_basis;
309     numeric * num_exponent;
310
311     if (is_exactly_of_type(*ebasis.bp,numeric)) {
312         basis_is_numerical=1;
313         num_basis=static_cast<numeric *>(ebasis.bp);
314     }
315     if (is_exactly_of_type(*eexponent.bp,numeric)) {
316         exponent_is_numerical=1;
317         num_exponent=static_cast<numeric *>(eexponent.bp);
318     }
319
320     // ^(x,0) -> 1 (0^0 also handled here)
321     if (eexponent.is_zero())
322         return exONE();
323
324     // ^(x,1) -> x
325     if (eexponent.is_equal(exONE()))
326         return ebasis;
327
328     // ^(0,x) -> 0 (except if x is real and negative)
329     if (ebasis.is_zero()) {
330         if (exponent_is_numerical && num_exponent->is_negative()) {
331             throw(std::overflow_error("power::eval(): division by zero"));
332         } else
333             return exZERO();
334     }
335
336     // ^(1,x) -> 1
337     if (ebasis.is_equal(exONE()))
338         return exONE();
339
340     if (basis_is_numerical && exponent_is_numerical) {
341         // ^(c1,c2) -> c1^c2 (c1, c2 numeric(),
342         // except if c1,c2 are rational, but c1^c2 is not)
343         bool basis_is_crational = num_basis->is_crational();
344         bool exponent_is_crational = num_exponent->is_crational();
345         numeric res = (*num_basis).power(*num_exponent);
346         
347         if ((!basis_is_crational || !exponent_is_crational)
348             || res.is_crational()) {
349             return res;
350         }
351         GINAC_ASSERT(!num_exponent->is_integer());  // has been handled by now
352         // ^(c1,n/m) -> *(c1^q,c1^(n/m-q)), 0<(n/m-h)<1, q integer
353         if (basis_is_crational && exponent_is_crational
354             && num_exponent->is_real()
355             && !num_exponent->is_integer()) {
356             numeric r, q, n, m;
357             n = num_exponent->numer();
358             m = num_exponent->denom();
359             q = iquo(n, m, r);
360             if (r.is_negative()) {
361                 r = r.add(m);
362                 q = q.sub(numONE());
363             }
364             if (q.is_zero())  // the exponent was in the allowed range 0<(n/m)<1
365                 return this->hold();
366             else {
367                 epvector res(2);
368                 res.push_back(expair(ebasis,r.div(m)));
369                 res.push_back(expair(ex(num_basis->power(q)),exONE()));
370                 return (new mul(res))->setflag(status_flags::dynallocated | status_flags::evaluated);
371                 /*return mul(num_basis->power(q),
372                            power(ex(*num_basis),ex(r.div(m)))).hold();
373                 */
374                 /* return (new mul(num_basis->power(q),
375                    power(*num_basis,r.div(m)).hold()))->setflag(status_flags::dynallocated | status_flags::evaluated);
376                 */
377             }
378         }
379     }
380
381     // ^(^(x,c1),c2) -> ^(x,c1*c2)
382     // (c1, c2 numeric(), c2 integer or -1 < c1 <= 1,
383     // case c1=1 should not happen, see below!)
384     if (exponent_is_numerical && is_ex_exactly_of_type(ebasis,power)) {
385         power const & sub_power=ex_to_power(ebasis);
386         ex const & sub_basis=sub_power.basis;
387         ex const & sub_exponent=sub_power.exponent;
388         if (is_ex_exactly_of_type(sub_exponent,numeric)) {
389             numeric const & num_sub_exponent=ex_to_numeric(sub_exponent);
390             GINAC_ASSERT(num_sub_exponent!=numeric(1));
391             if (num_exponent->is_integer() || abs(num_sub_exponent)<1) {
392                 return power(sub_basis,num_sub_exponent.mul(*num_exponent));
393             }
394         }
395     }
396     
397     // ^(*(x,y,z),c1) -> *(x^c1,y^c1,z^c1) (c1 integer)
398     if (exponent_is_numerical && num_exponent->is_integer() &&
399         is_ex_exactly_of_type(ebasis,mul)) {
400         return expand_mul(ex_to_mul(ebasis), *num_exponent);
401     }
402
403     // ^(*(...,x;c1),c2) -> ^(*(...,x;1),c2)*c1^c2 (c1, c2 numeric(), c1>0)
404     // ^(*(...,x,c1),c2) -> ^(*(...,x;-1),c2)*(-c1)^c2 (c1, c2 numeric(), c1<0)
405     if (exponent_is_numerical && is_ex_exactly_of_type(ebasis,mul)) {
406         GINAC_ASSERT(!num_exponent->is_integer()); // should have been handled above
407         mul const & mulref=ex_to_mul(ebasis);
408         if (!mulref.overall_coeff.is_equal(exONE())) {
409             numeric const & num_coeff=ex_to_numeric(mulref.overall_coeff);
410             if (num_coeff.is_real()) {
411                 if (num_coeff.is_positive()>0) {
412                     mul * mulp=new mul(mulref);
413                     mulp->overall_coeff=exONE();
414                     mulp->clearflag(status_flags::evaluated);
415                     mulp->clearflag(status_flags::hash_calculated);
416                     return (new mul(power(*mulp,exponent),
417                                     power(num_coeff,*num_exponent)))->
418                         setflag(status_flags::dynallocated);
419                 } else {
420                     GINAC_ASSERT(num_coeff.compare(numZERO())<0);
421                     if (num_coeff.compare(numMINUSONE())!=0) {
422                         mul * mulp=new mul(mulref);
423                         mulp->overall_coeff=exMINUSONE();
424                         mulp->clearflag(status_flags::evaluated);
425                         mulp->clearflag(status_flags::hash_calculated);
426                         return (new mul(power(*mulp,exponent),
427                                         power(abs(num_coeff),*num_exponent)))->
428                             setflag(status_flags::dynallocated);
429                     }
430                 }
431             }
432         }
433     }
434         
435     if (are_ex_trivially_equal(ebasis,basis) &&
436         are_ex_trivially_equal(eexponent,exponent)) {
437         return this->hold();
438     }
439     return (new power(ebasis, eexponent))->setflag(status_flags::dynallocated |
440                                                    status_flags::evaluated);
441 }
442
443 ex power::evalf(int level) const
444 {
445     debugmsg("power evalf",LOGLEVEL_MEMBER_FUNCTION);
446
447     ex ebasis;
448     ex eexponent;
449     
450     if (level==1) {
451         ebasis=basis;
452         eexponent=exponent;
453     } else if (level == -max_recursion_level) {
454         throw(std::runtime_error("max recursion level reached"));
455     } else {
456         ebasis=basis.evalf(level-1);
457         eexponent=exponent.evalf(level-1);
458     }
459
460     return power(ebasis,eexponent);
461 }
462
463 ex power::subs(lst const & ls, lst const & lr) const
464 {
465     ex const & subsed_basis=basis.subs(ls,lr);
466     ex const & subsed_exponent=exponent.subs(ls,lr);
467
468     if (are_ex_trivially_equal(basis,subsed_basis)&&
469         are_ex_trivially_equal(exponent,subsed_exponent)) {
470         return *this;
471     }
472     
473     return power(subsed_basis, subsed_exponent);
474 }
475
476 ex power::simplify_ncmul(exvector const & v) const
477 {
478     return basic::simplify_ncmul(v);
479 }
480
481 // protected
482
483 int power::compare_same_type(basic const & other) const
484 {
485     GINAC_ASSERT(is_exactly_of_type(other, power));
486     power const & o=static_cast<power const &>(const_cast<basic &>(other));
487
488     int cmpval;
489     cmpval=basis.compare(o.basis);
490     if (cmpval==0) {
491         return exponent.compare(o.exponent);
492     }
493     return cmpval;
494 }
495
496 unsigned power::return_type(void) const
497 {
498     return basis.return_type();
499 }
500    
501 unsigned power::return_type_tinfo(void) const
502 {
503     return basis.return_type_tinfo();
504 }
505
506 ex power::expand(unsigned options) const
507 {
508     ex expanded_basis=basis.expand(options);
509
510     if (!is_ex_exactly_of_type(exponent,numeric)||
511         !ex_to_numeric(exponent).is_integer()) {
512         if (are_ex_trivially_equal(basis,expanded_basis)) {
513             return this->hold();
514         } else {
515             return (new power(expanded_basis,exponent))->
516                     setflag(status_flags::dynallocated);
517         }
518     }
519
520     // integer numeric exponent
521     numeric const & num_exponent=ex_to_numeric(exponent);
522     int int_exponent = num_exponent.to_int();
523
524     if (int_exponent > 0 && is_ex_exactly_of_type(expanded_basis,add)) {
525         return expand_add(ex_to_add(expanded_basis), int_exponent);
526     }
527
528     if (is_ex_exactly_of_type(expanded_basis,mul)) {
529         return expand_mul(ex_to_mul(expanded_basis), num_exponent);
530     }
531
532     // cannot expand further
533     if (are_ex_trivially_equal(basis,expanded_basis)) {
534         return this->hold();
535     } else {
536         return (new power(expanded_basis,exponent))->
537                setflag(status_flags::dynallocated);
538     }
539 }
540
541 //////////
542 // new virtual functions which can be overridden by derived classes
543 //////////
544
545 // none
546
547 //////////
548 // non-virtual functions in this class
549 //////////
550
551 ex power::expand_add(add const & a, int const n) const
552 {
553     // expand a^n where a is an add and n is an integer
554
555     if (n==2) {
556         return expand_add_2(a);
557     }
558     
559     int m=a.nops();
560     exvector sum;
561     sum.reserve((n+1)*(m-1));
562     intvector k(m-1);
563     intvector k_cum(m-1); // k_cum[l]:=sum(i=0,l,k[l]);
564     intvector upper_limit(m-1);
565     int l;
566     
567     for (int l=0; l<m-1; l++) {
568         k[l]=0;
569         k_cum[l]=0;
570         upper_limit[l]=n;
571     }
572
573     while (1) {
574         exvector term;
575         term.reserve(m+1);
576         for (l=0; l<m-1; l++) {
577             ex const & b=a.op(l);
578             GINAC_ASSERT(!is_ex_exactly_of_type(b,add));
579             GINAC_ASSERT(!is_ex_exactly_of_type(b,power)||
580                    !is_ex_exactly_of_type(ex_to_power(b).exponent,numeric)||
581                    !ex_to_numeric(ex_to_power(b).exponent).is_pos_integer());
582             if (is_ex_exactly_of_type(b,mul)) {
583                 term.push_back(expand_mul(ex_to_mul(b),numeric(k[l])));
584             } else {
585                 term.push_back(power(b,k[l]));
586             }
587         }
588
589         ex const & b=a.op(l);
590         GINAC_ASSERT(!is_ex_exactly_of_type(b,add));
591         GINAC_ASSERT(!is_ex_exactly_of_type(b,power)||
592                !is_ex_exactly_of_type(ex_to_power(b).exponent,numeric)||
593                !ex_to_numeric(ex_to_power(b).exponent).is_pos_integer());
594         if (is_ex_exactly_of_type(b,mul)) {
595             term.push_back(expand_mul(ex_to_mul(b),numeric(n-k_cum[m-2])));
596         } else {
597             term.push_back(power(b,n-k_cum[m-2]));
598         }
599
600         numeric f=binomial(numeric(n),numeric(k[0]));
601         for (l=1; l<m-1; l++) {
602             f=f*binomial(numeric(n-k_cum[l-1]),numeric(k[l]));
603         }
604         term.push_back(f);
605
606         /*
607         cout << "begin term" << endl;
608         for (int i=0; i<m-1; i++) {
609             cout << "k[" << i << "]=" << k[i] << endl;
610             cout << "k_cum[" << i << "]=" << k_cum[i] << endl;
611             cout << "upper_limit[" << i << "]=" << upper_limit[i] << endl;
612         }
613         for (exvector::const_iterator cit=term.begin(); cit!=term.end(); ++cit) {
614             cout << *cit << endl;
615         }
616         cout << "end term" << endl;
617         */
618
619         // TODO: optimize this
620         sum.push_back((new mul(term))->setflag(status_flags::dynallocated));
621         
622         // increment k[]
623         l=m-2;
624         while ((l>=0)&&((++k[l])>upper_limit[l])) {
625             k[l]=0;    
626             l--;
627         }
628         if (l<0) break;
629
630         // recalc k_cum[] and upper_limit[]
631         if (l==0) {
632             k_cum[0]=k[0];
633         } else {
634             k_cum[l]=k_cum[l-1]+k[l];
635         }
636         for (int i=l+1; i<m-1; i++) {
637             k_cum[i]=k_cum[i-1]+k[i];
638         }
639
640         for (int i=l+1; i<m-1; i++) {
641             upper_limit[i]=n-k_cum[i-1];
642         }   
643     }
644     return (new add(sum))->setflag(status_flags::dynallocated);
645 }
646
647 /*
648 ex power::expand_add_2(add const & a) const
649 {
650     // special case: expand a^2 where a is an add
651
652     epvector sum;
653     sum.reserve((a.seq.size()*(a.seq.size()+1))/2);
654     epvector::const_iterator last=a.seq.end();
655
656     for (epvector::const_iterator cit0=a.seq.begin(); cit0!=last; ++cit0) {
657         ex const & b=a.recombine_pair_to_ex(*cit0);
658         GINAC_ASSERT(!is_ex_exactly_of_type(b,add));
659         GINAC_ASSERT(!is_ex_exactly_of_type(b,power)||
660                !is_ex_exactly_of_type(ex_to_power(b).exponent,numeric)||
661                !ex_to_numeric(ex_to_power(b).exponent).is_pos_integer());
662         if (is_ex_exactly_of_type(b,mul)) {
663             sum.push_back(a.split_ex_to_pair(expand_mul(ex_to_mul(b),numTWO())));
664         } else {
665             sum.push_back(a.split_ex_to_pair((new power(b,exTWO()))->
666                                               setflag(status_flags::dynallocated)));
667         }
668         for (epvector::const_iterator cit1=cit0+1; cit1!=last; ++cit1) {
669             sum.push_back(a.split_ex_to_pair((new mul(a.recombine_pair_to_ex(*cit0),
670                                                       a.recombine_pair_to_ex(*cit1)))->
671                                               setflag(status_flags::dynallocated),
672                                              exTWO()));
673         }
674     }
675
676     GINAC_ASSERT(sum.size()==(a.seq.size()*(a.seq.size()+1))/2);
677
678     return (new add(sum))->setflag(status_flags::dynallocated);
679 }
680 */
681
682 ex power::expand_add_2(add const & a) const
683 {
684     // special case: expand a^2 where a is an add
685
686     epvector sum;
687     unsigned a_nops=a.nops();
688     sum.reserve((a_nops*(a_nops+1))/2);
689     epvector::const_iterator last=a.seq.end();
690
691     // power(+(x,...,z;c),2)=power(+(x,...,z;0),2)+2*c*+(x,...,z;0)+c*c
692     // first part: ignore overall_coeff and expand other terms
693     for (epvector::const_iterator cit0=a.seq.begin(); cit0!=last; ++cit0) {
694         ex const & r=(*cit0).rest;
695         ex const & c=(*cit0).coeff;
696         
697         GINAC_ASSERT(!is_ex_exactly_of_type(r,add));
698         GINAC_ASSERT(!is_ex_exactly_of_type(r,power)||
699                !is_ex_exactly_of_type(ex_to_power(r).exponent,numeric)||
700                !ex_to_numeric(ex_to_power(r).exponent).is_pos_integer()||
701                !is_ex_exactly_of_type(ex_to_power(r).basis,add)||
702                !is_ex_exactly_of_type(ex_to_power(r).basis,mul)||
703                !is_ex_exactly_of_type(ex_to_power(r).basis,power));
704
705         if (are_ex_trivially_equal(c,exONE())) {
706             if (is_ex_exactly_of_type(r,mul)) {
707                 sum.push_back(expair(expand_mul(ex_to_mul(r),numTWO()),exONE()));
708             } else {
709                 sum.push_back(expair((new power(r,exTWO()))->setflag(status_flags::dynallocated),
710                                      exONE()));
711             }
712         } else {
713             if (is_ex_exactly_of_type(r,mul)) {
714                 sum.push_back(expair(expand_mul(ex_to_mul(r),numTWO()),
715                                      ex_to_numeric(c).power_dyn(numTWO())));
716             } else {
717                 sum.push_back(expair((new power(r,exTWO()))->setflag(status_flags::dynallocated),
718                                      ex_to_numeric(c).power_dyn(numTWO())));
719             }
720         }
721             
722         for (epvector::const_iterator cit1=cit0+1; cit1!=last; ++cit1) {
723             ex const & r1=(*cit1).rest;
724             ex const & c1=(*cit1).coeff;
725             sum.push_back(a.combine_ex_with_coeff_to_pair((new mul(r,r1))->setflag(status_flags::dynallocated),
726                                                           numTWO().mul(ex_to_numeric(c)).mul_dyn(ex_to_numeric(c1))));
727         }
728     }
729
730     GINAC_ASSERT(sum.size()==(a.seq.size()*(a.seq.size()+1))/2);
731
732     // second part: add terms coming from overall_factor (if != 0)
733     if (!a.overall_coeff.is_equal(exZERO())) {
734         for (epvector::const_iterator cit=a.seq.begin(); cit!=a.seq.end(); ++cit) {
735             sum.push_back(a.combine_pair_with_coeff_to_pair(*cit,ex_to_numeric(a.overall_coeff).mul_dyn(numTWO())));
736         }
737         sum.push_back(expair(ex_to_numeric(a.overall_coeff).power_dyn(numTWO()),exONE()));
738     }
739         
740     GINAC_ASSERT(sum.size()==(a_nops*(a_nops+1))/2);
741     
742     return (new add(sum))->setflag(status_flags::dynallocated);
743 }
744
745 ex power::expand_mul(mul const & m, numeric const & n) const
746 {
747     // expand m^n where m is a mul and n is and integer
748
749     if (n.is_equal(numZERO())) {
750         return exONE();
751     }
752     
753     epvector distrseq;
754     distrseq.reserve(m.seq.size());
755     epvector::const_iterator last=m.seq.end();
756     epvector::const_iterator cit=m.seq.begin();
757     while (cit!=last) {
758         if (is_ex_exactly_of_type((*cit).rest,numeric)) {
759             distrseq.push_back(m.combine_pair_with_coeff_to_pair(*cit,n));
760         } else {
761             // it is safe not to call mul::combine_pair_with_coeff_to_pair()
762             // since n is an integer
763             distrseq.push_back(expair((*cit).rest,
764                                       ex_to_numeric((*cit).coeff).mul(n)));
765         }
766         ++cit;
767     }
768     return (new mul(distrseq,ex_to_numeric(m.overall_coeff).power_dyn(n)))
769                  ->setflag(status_flags::dynallocated);
770 }
771
772 /*
773 ex power::expand_commutative_3(ex const & basis, numeric const & exponent,
774                              unsigned options) const
775 {
776     // obsolete
777
778     exvector distrseq;
779     epvector splitseq;
780
781     add const & addref=static_cast<add const &>(*basis.bp);
782
783     splitseq=addref.seq;
784     splitseq.pop_back();
785     ex first_operands=add(splitseq);
786     ex last_operand=addref.recombine_pair_to_ex(*(addref.seq.end()-1));
787     
788     int n=exponent.to_int();
789     for (int k=0; k<=n; k++) {
790         distrseq.push_back(binomial(n,k)*power(first_operands,numeric(k))*
791                            power(last_operand,numeric(n-k)));
792     }
793     return ex((new add(distrseq))->setflag(status_flags::sub_expanded |
794                                            status_flags::expanded |
795                                            status_flags::dynallocated  )).
796            expand(options);
797 }
798 */
799
800 /*
801 ex power::expand_noncommutative(ex const & basis, numeric const & exponent,
802                                 unsigned options) const
803 {
804     ex rest_power=ex(power(basis,exponent.add(numMINUSONE()))).
805                   expand(options | expand_options::internal_do_not_expand_power_operands);
806
807     return ex(mul(rest_power,basis),0).
808            expand(options | expand_options::internal_do_not_expand_mul_operands);
809 }
810 */
811
812 //////////
813 // static member variables
814 //////////
815
816 // protected
817
818 unsigned power::precedence=60;
819
820 //////////
821 // global constants
822 //////////
823
824 const power some_power;
825 type_info const & typeid_power=typeid(some_power);
826
827 #ifndef NO_GINAC_NAMESPACE
828 } // namespace GiNaC
829 #endif // ndef NO_GINAC_NAMESPACE