3 * Implementation of GiNaC's products of expressions. */
6 * GiNaC Copyright (C) 1999-2002 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
36 GINAC_IMPLEMENT_REGISTERED_CLASS(mul, expairseq)
39 // default ctor, dtor, copy ctor, assignment operator and helpers
44 tinfo_key = TINFO_mul;
56 mul::mul(const ex & lh, const ex & rh)
58 tinfo_key = TINFO_mul;
60 construct_from_2_ex(lh,rh);
61 GINAC_ASSERT(is_canonical());
64 mul::mul(const exvector & v)
66 tinfo_key = TINFO_mul;
68 construct_from_exvector(v);
69 GINAC_ASSERT(is_canonical());
72 mul::mul(const epvector & v)
74 tinfo_key = TINFO_mul;
76 construct_from_epvector(v);
77 GINAC_ASSERT(is_canonical());
80 mul::mul(const epvector & v, const ex & oc)
82 tinfo_key = TINFO_mul;
84 construct_from_epvector(v);
85 GINAC_ASSERT(is_canonical());
88 mul::mul(epvector * vp, const ex & oc)
90 tinfo_key = TINFO_mul;
93 construct_from_epvector(*vp);
95 GINAC_ASSERT(is_canonical());
98 mul::mul(const ex & lh, const ex & mh, const ex & rh)
100 tinfo_key = TINFO_mul;
103 factors.push_back(lh);
104 factors.push_back(mh);
105 factors.push_back(rh);
106 overall_coeff = _ex1;
107 construct_from_exvector(factors);
108 GINAC_ASSERT(is_canonical());
115 DEFAULT_ARCHIVING(mul)
118 // functions overriding virtual functions from base classes
123 void mul::print(const print_context & c, unsigned level) const
125 if (is_a<print_tree>(c)) {
127 inherited::print(c, level);
129 } else if (is_a<print_csrc>(c)) {
131 if (precedence() <= level)
134 if (!overall_coeff.is_equal(_ex1)) {
135 overall_coeff.print(c, precedence());
139 // Print arguments, separated by "*" or "/"
140 epvector::const_iterator it = seq.begin(), itend = seq.end();
141 while (it != itend) {
143 // If the first argument is a negative integer power, it gets printed as "1.0/<expr>"
144 bool needclosingparenthesis = false;
145 if (it == seq.begin() && it->coeff.info(info_flags::negint)) {
146 if (is_a<print_csrc_cl_N>(c)) {
148 needclosingparenthesis = true;
153 // If the exponent is 1 or -1, it is left out
154 if (it->coeff.is_equal(_ex1) || it->coeff.is_equal(_ex_1))
155 it->rest.print(c, precedence());
156 else if (it->coeff.info(info_flags::negint))
157 // Outer parens around ex needed for broken gcc-2.95 parser:
158 (ex(power(it->rest, -ex_to<numeric>(it->coeff)))).print(c, level);
160 // Outer parens around ex needed for broken gcc-2.95 parser:
161 (ex(power(it->rest, ex_to<numeric>(it->coeff)))).print(c, level);
163 if (needclosingparenthesis)
166 // Separator is "/" for negative integer powers, "*" otherwise
169 if (it->coeff.info(info_flags::negint))
176 if (precedence() <= level)
179 } else if (is_a<print_python_repr>(c)) {
180 c.s << class_name() << '(';
182 for (unsigned i=1; i<nops(); ++i) {
189 if (precedence() <= level) {
190 if (is_a<print_latex>(c))
198 // First print the overall numeric coefficient
199 numeric coeff = ex_to<numeric>(overall_coeff);
200 if (coeff.csgn() == -1)
202 if (!coeff.is_equal(_num1) &&
203 !coeff.is_equal(_num_1)) {
204 if (coeff.is_rational()) {
205 if (coeff.is_negative())
210 if (coeff.csgn() == -1)
211 (-coeff).print(c, precedence());
213 coeff.print(c, precedence());
215 if (is_a<print_latex>(c))
221 // Then proceed with the remaining factors
222 epvector::const_iterator it = seq.begin(), itend = seq.end();
223 while (it != itend) {
225 if (is_a<print_latex>(c))
232 recombine_pair_to_ex(*it).print(c, precedence());
236 if (precedence() <= level) {
237 if (is_a<print_latex>(c))
245 bool mul::info(unsigned inf) const
248 case info_flags::polynomial:
249 case info_flags::integer_polynomial:
250 case info_flags::cinteger_polynomial:
251 case info_flags::rational_polynomial:
252 case info_flags::crational_polynomial:
253 case info_flags::rational_function: {
254 epvector::const_iterator i = seq.begin(), end = seq.end();
256 if (!(recombine_pair_to_ex(*i).info(inf)))
260 return overall_coeff.info(inf);
262 case info_flags::algebraic: {
263 epvector::const_iterator i = seq.begin(), end = seq.end();
265 if ((recombine_pair_to_ex(*i).info(inf)))
272 return inherited::info(inf);
275 int mul::degree(const ex & s) const
277 // Sum up degrees of factors
279 epvector::const_iterator i = seq.begin(), end = seq.end();
281 if (ex_to<numeric>(i->coeff).is_integer())
282 deg_sum += i->rest.degree(s) * ex_to<numeric>(i->coeff).to_int();
288 int mul::ldegree(const ex & s) const
290 // Sum up degrees of factors
292 epvector::const_iterator i = seq.begin(), end = seq.end();
294 if (ex_to<numeric>(i->coeff).is_integer())
295 deg_sum += i->rest.ldegree(s) * ex_to<numeric>(i->coeff).to_int();
301 ex mul::coeff(const ex & s, int n) const
304 coeffseq.reserve(seq.size()+1);
307 // product of individual coeffs
308 // if a non-zero power of s is found, the resulting product will be 0
309 epvector::const_iterator i = seq.begin(), end = seq.end();
311 coeffseq.push_back(recombine_pair_to_ex(*i).coeff(s,n));
314 coeffseq.push_back(overall_coeff);
315 return (new mul(coeffseq))->setflag(status_flags::dynallocated);
318 epvector::const_iterator i = seq.begin(), end = seq.end();
319 bool coeff_found = false;
321 ex t = recombine_pair_to_ex(*i);
322 ex c = t.coeff(s, n);
324 coeffseq.push_back(c);
327 coeffseq.push_back(t);
332 coeffseq.push_back(overall_coeff);
333 return (new mul(coeffseq))->setflag(status_flags::dynallocated);
339 /** Perform automatic term rewriting rules in this class. In the following
340 * x, x1, x2,... stand for a symbolic variables of type ex and c, c1, c2...
341 * stand for such expressions that contain a plain number.
343 * - *(+(x1,x2,...);c) -> *(+(*(x1,c),*(x2,c),...))
347 * @param level cut-off in recursive evaluation */
348 ex mul::eval(int level) const
350 epvector *evaled_seqp = evalchildren(level);
352 // do more evaluation later
353 return (new mul(evaled_seqp,overall_coeff))->
354 setflag(status_flags::dynallocated);
357 #ifdef DO_GINAC_ASSERT
358 epvector::const_iterator i = seq.begin(), end = seq.end();
360 GINAC_ASSERT((!is_exactly_a<mul>(i->rest)) ||
361 (!(ex_to<numeric>(i->coeff).is_integer())));
362 GINAC_ASSERT(!(i->is_canonical_numeric()));
363 if (is_ex_exactly_of_type(recombine_pair_to_ex(*i), numeric))
364 print(print_tree(std::cerr));
365 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*i)));
367 expair p = split_ex_to_pair(recombine_pair_to_ex(*i));
368 GINAC_ASSERT(p.rest.is_equal(i->rest));
369 GINAC_ASSERT(p.coeff.is_equal(i->coeff));
373 #endif // def DO_GINAC_ASSERT
375 if (flags & status_flags::evaluated) {
376 GINAC_ASSERT(seq.size()>0);
377 GINAC_ASSERT(seq.size()>1 || !overall_coeff.is_equal(_ex1));
381 int seq_size = seq.size();
382 if (overall_coeff.is_zero()) {
385 } else if (seq_size==0) {
387 return overall_coeff;
388 } else if (seq_size==1 && overall_coeff.is_equal(_ex1)) {
390 return recombine_pair_to_ex(*(seq.begin()));
391 } else if ((seq_size==1) &&
392 is_ex_exactly_of_type((*seq.begin()).rest,add) &&
393 ex_to<numeric>((*seq.begin()).coeff).is_equal(_num1)) {
394 // *(+(x,y,...);c) -> +(*(x,c),*(y,c),...) (c numeric(), no powers of +())
395 const add & addref = ex_to<add>((*seq.begin()).rest);
396 epvector *distrseq = new epvector();
397 distrseq->reserve(addref.seq.size());
398 epvector::const_iterator i = addref.seq.begin(), end = addref.seq.end();
400 distrseq->push_back(addref.combine_pair_with_coeff_to_pair(*i, overall_coeff));
403 return (new add(distrseq,
404 ex_to<numeric>(addref.overall_coeff).
405 mul_dyn(ex_to<numeric>(overall_coeff))))
406 ->setflag(status_flags::dynallocated | status_flags::evaluated);
411 ex mul::evalf(int level) const
414 return mul(seq,overall_coeff);
416 if (level==-max_recursion_level)
417 throw(std::runtime_error("max recursion level reached"));
419 epvector *s = new epvector();
420 s->reserve(seq.size());
423 epvector::const_iterator i = seq.begin(), end = seq.end();
425 s->push_back(combine_ex_with_coeff_to_pair(i->rest.evalf(level),
429 return mul(s, overall_coeff.evalf(level));
432 ex mul::evalm(void) const
435 if (seq.size() == 1 && seq[0].coeff.is_equal(_ex1)
436 && is_ex_of_type(seq[0].rest, matrix))
437 return ex_to<matrix>(seq[0].rest).mul(ex_to<numeric>(overall_coeff));
439 // Evaluate children first, look whether there are any matrices at all
440 // (there can be either no matrices or one matrix; if there were more
441 // than one matrix, it would be a non-commutative product)
442 epvector *s = new epvector;
443 s->reserve(seq.size());
445 bool have_matrix = false;
446 epvector::iterator the_matrix;
448 epvector::const_iterator i = seq.begin(), end = seq.end();
450 const ex &m = recombine_pair_to_ex(*i).evalm();
451 s->push_back(split_ex_to_pair(m));
452 if (is_ex_of_type(m, matrix)) {
454 the_matrix = s->end() - 1;
461 // The product contained a matrix. We will multiply all other factors
463 matrix m = ex_to<matrix>(the_matrix->rest);
464 s->erase(the_matrix);
465 ex scalar = (new mul(s, overall_coeff))->setflag(status_flags::dynallocated);
466 return m.mul_scalar(scalar);
469 return (new mul(s, overall_coeff))->setflag(status_flags::dynallocated);
472 ex mul::simplify_ncmul(const exvector & v) const
475 return inherited::simplify_ncmul(v);
477 // Find first noncommutative element and call its simplify_ncmul()
478 epvector::const_iterator i = seq.begin(), end = seq.end();
480 if (i->rest.return_type() == return_types::noncommutative)
481 return i->rest.simplify_ncmul(v);
484 return inherited::simplify_ncmul(v);
489 /** Implementation of ex::diff() for a product. It applies the product rule.
491 ex mul::derivative(const symbol & s) const
493 unsigned num = seq.size();
497 // D(a*b*c) = D(a)*b*c + a*D(b)*c + a*b*D(c)
498 epvector mulseq = seq;
499 epvector::const_iterator i = seq.begin(), end = seq.end();
500 epvector::iterator i2 = mulseq.begin();
502 expair ep = split_ex_to_pair(power(i->rest, i->coeff - _ex1) *
505 addseq.push_back((new mul(mulseq, overall_coeff * i->coeff))->setflag(status_flags::dynallocated));
509 return (new add(addseq))->setflag(status_flags::dynallocated);
512 int mul::compare_same_type(const basic & other) const
514 return inherited::compare_same_type(other);
517 bool mul::is_equal_same_type(const basic & other) const
519 return inherited::is_equal_same_type(other);
522 unsigned mul::return_type(void) const
525 // mul without factors: should not happen, but commutes
526 return return_types::commutative;
529 bool all_commutative = true;
530 epvector::const_iterator noncommutative_element; // point to first found nc element
532 epvector::const_iterator i = seq.begin(), end = seq.end();
534 unsigned rt = i->rest.return_type();
535 if (rt == return_types::noncommutative_composite)
536 return rt; // one ncc -> mul also ncc
537 if ((rt == return_types::noncommutative) && (all_commutative)) {
538 // first nc element found, remember position
539 noncommutative_element = i;
540 all_commutative = false;
542 if ((rt == return_types::noncommutative) && (!all_commutative)) {
543 // another nc element found, compare type_infos
544 if (noncommutative_element->rest.return_type_tinfo() != i->rest.return_type_tinfo()) {
545 // diffent types -> mul is ncc
546 return return_types::noncommutative_composite;
551 // all factors checked
552 return all_commutative ? return_types::commutative : return_types::noncommutative;
555 unsigned mul::return_type_tinfo(void) const
558 return tinfo_key; // mul without factors: should not happen
560 // return type_info of first noncommutative element
561 epvector::const_iterator i = seq.begin(), end = seq.end();
563 if (i->rest.return_type() == return_types::noncommutative)
564 return i->rest.return_type_tinfo();
567 // no noncommutative element found, should not happen
571 ex mul::thisexpairseq(const epvector & v, const ex & oc) const
573 return (new mul(v, oc))->setflag(status_flags::dynallocated);
576 ex mul::thisexpairseq(epvector * vp, const ex & oc) const
578 return (new mul(vp, oc))->setflag(status_flags::dynallocated);
581 expair mul::split_ex_to_pair(const ex & e) const
583 if (is_ex_exactly_of_type(e,power)) {
584 const power & powerref = ex_to<power>(e);
585 if (is_ex_exactly_of_type(powerref.exponent,numeric))
586 return expair(powerref.basis,powerref.exponent);
588 return expair(e,_ex1);
591 expair mul::combine_ex_with_coeff_to_pair(const ex & e,
594 // to avoid duplication of power simplification rules,
595 // we create a temporary power object
596 // otherwise it would be hard to correctly simplify
597 // expression like (4^(1/3))^(3/2)
598 if (are_ex_trivially_equal(c,_ex1))
599 return split_ex_to_pair(e);
601 return split_ex_to_pair(power(e,c));
604 expair mul::combine_pair_with_coeff_to_pair(const expair & p,
607 // to avoid duplication of power simplification rules,
608 // we create a temporary power object
609 // otherwise it would be hard to correctly simplify
610 // expression like (4^(1/3))^(3/2)
611 if (are_ex_trivially_equal(c,_ex1))
614 return split_ex_to_pair(power(recombine_pair_to_ex(p),c));
617 ex mul::recombine_pair_to_ex(const expair & p) const
619 if (ex_to<numeric>(p.coeff).is_equal(_num1))
622 return power(p.rest,p.coeff);
625 bool mul::expair_needs_further_processing(epp it)
627 if (is_ex_exactly_of_type((*it).rest,mul) &&
628 ex_to<numeric>((*it).coeff).is_integer()) {
629 // combined pair is product with integer power -> expand it
630 *it = split_ex_to_pair(recombine_pair_to_ex(*it));
633 if (is_ex_exactly_of_type((*it).rest,numeric)) {
634 expair ep=split_ex_to_pair(recombine_pair_to_ex(*it));
635 if (!ep.is_equal(*it)) {
636 // combined pair is a numeric power which can be simplified
640 if (ex_to<numeric>((*it).coeff).is_equal(_num1)) {
641 // combined pair has coeff 1 and must be moved to the end
648 ex mul::default_overall_coeff(void) const
653 void mul::combine_overall_coeff(const ex & c)
655 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
656 GINAC_ASSERT(is_exactly_a<numeric>(c));
657 overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c));
660 void mul::combine_overall_coeff(const ex & c1, const ex & c2)
662 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
663 GINAC_ASSERT(is_exactly_a<numeric>(c1));
664 GINAC_ASSERT(is_exactly_a<numeric>(c2));
665 overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c1).power(ex_to<numeric>(c2)));
668 bool mul::can_make_flat(const expair & p) const
670 GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
671 // this assertion will probably fail somewhere
672 // it would require a more careful make_flat, obeying the power laws
673 // probably should return true only if p.coeff is integer
674 return ex_to<numeric>(p.coeff).is_equal(_num1);
677 ex mul::expand(unsigned options) const
679 // First, expand the children
680 epvector * expanded_seqp = expandchildren(options);
681 const epvector & expanded_seq = (expanded_seqp == NULL) ? seq : *expanded_seqp;
683 // Now, look for all the factors that are sums and multiply each one out
684 // with the next one that is found while collecting the factors which are
686 int number_of_adds = 0;
687 ex last_expanded = _ex1;
689 non_adds.reserve(expanded_seq.size());
690 epvector::const_iterator cit = expanded_seq.begin(), last = expanded_seq.end();
691 while (cit != last) {
692 if (is_ex_exactly_of_type(cit->rest, add) &&
693 (cit->coeff.is_equal(_ex1))) {
695 if (is_ex_exactly_of_type(last_expanded, add)) {
697 // Expand a product of two sums, simple and robust version.
698 const add & add1 = ex_to<add>(last_expanded);
699 const add & add2 = ex_to<add>(cit->rest);
700 const int n1 = add1.nops();
701 const int n2 = add2.nops();
704 distrseq.reserve(n2);
705 for (int i1=0; i1<n1; ++i1) {
707 // cache the first operand (for efficiency):
708 const ex op1 = add1.op(i1);
709 for (int i2=0; i2<n2; ++i2)
710 distrseq.push_back(op1 * add2.op(i2));
711 tmp_accu += (new add(distrseq))->
712 setflag(status_flags::dynallocated);
714 last_expanded = tmp_accu;
716 // Expand a product of two sums, aggressive version.
717 // Caring for the overall coefficients in separate loops can
718 // sometimes give a performance gain of up to 15%!
720 const int sizedifference = ex_to<add>(last_expanded).seq.size()-ex_to<add>(cit->rest).seq.size();
721 // add2 is for the inner loop and should be the bigger of the two sums
722 // in the presence of asymptotically good sorting:
723 const add& add1 = (sizedifference<0 ? ex_to<add>(last_expanded) : ex_to<add>(cit->rest));
724 const add& add2 = (sizedifference<0 ? ex_to<add>(cit->rest) : ex_to<add>(last_expanded));
725 const epvector::const_iterator add1begin = add1.seq.begin();
726 const epvector::const_iterator add1end = add1.seq.end();
727 const epvector::const_iterator add2begin = add2.seq.begin();
728 const epvector::const_iterator add2end = add2.seq.end();
730 distrseq.reserve(add1.seq.size()+add2.seq.size());
731 // Multiply add2 with the overall coefficient of add1 and append it to distrseq:
732 if (!add1.overall_coeff.is_zero()) {
733 if (add1.overall_coeff.is_equal(_ex1))
734 distrseq.insert(distrseq.end(),add2begin,add2end);
736 for (epvector::const_iterator i=add2begin; i!=add2end; ++i)
737 distrseq.push_back(expair(i->rest, ex_to<numeric>(i->coeff).mul_dyn(ex_to<numeric>(add1.overall_coeff))));
739 // Multiply add1 with the overall coefficient of add2 and append it to distrseq:
740 if (!add2.overall_coeff.is_zero()) {
741 if (add2.overall_coeff.is_equal(_ex1))
742 distrseq.insert(distrseq.end(),add1begin,add1end);
744 for (epvector::const_iterator i=add1begin; i!=add1end; ++i)
745 distrseq.push_back(expair(i->rest, ex_to<numeric>(i->coeff).mul_dyn(ex_to<numeric>(add2.overall_coeff))));
747 // Compute the new overall coefficient and put it together:
748 ex tmp_accu = (new add(distrseq, add1.overall_coeff*add2.overall_coeff))->setflag(status_flags::dynallocated);
749 // Multiply explicitly all non-numeric terms of add1 and add2:
750 for (epvector::const_iterator i1=add1begin; i1!=add1end; ++i1) {
751 // We really have to combine terms here in order to compactify
752 // the result. Otherwise it would become waayy tooo bigg.
755 for (epvector::const_iterator i2=add2begin; i2!=add2end; ++i2) {
756 // Don't push_back expairs which might have a rest that evaluates to a numeric,
757 // since that would violate an invariant of expairseq:
758 const ex rest = (new mul(i1->rest, i2->rest))->setflag(status_flags::dynallocated);
759 if (is_ex_exactly_of_type(rest, numeric))
760 oc += ex_to<numeric>(rest).mul(ex_to<numeric>(i1->coeff).mul(ex_to<numeric>(i2->coeff)));
762 distrseq.push_back(expair(rest, ex_to<numeric>(i1->coeff).mul_dyn(ex_to<numeric>(i2->coeff))));
764 tmp_accu += (new add(distrseq, oc))->setflag(status_flags::dynallocated);
766 last_expanded = tmp_accu;
769 non_adds.push_back(split_ex_to_pair(last_expanded));
770 last_expanded = cit->rest;
773 non_adds.push_back(*cit);
778 delete expanded_seqp;
780 // Now the only remaining thing to do is to multiply the factors which
781 // were not sums into the "last_expanded" sum
782 if (is_ex_exactly_of_type(last_expanded, add)) {
783 const add & finaladd = ex_to<add>(last_expanded);
785 int n = finaladd.nops();
787 for (int i=0; i<n; ++i) {
788 epvector factors = non_adds;
789 factors.push_back(split_ex_to_pair(finaladd.op(i)));
790 distrseq.push_back((new mul(factors, overall_coeff))->
791 setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0)));
793 return ((new add(distrseq))->
794 setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0)));
796 non_adds.push_back(split_ex_to_pair(last_expanded));
797 return (new mul(non_adds, overall_coeff))->
798 setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
803 // new virtual functions which can be overridden by derived classes
809 // non-virtual functions in this class
813 /** Member-wise expand the expairs representing this sequence. This must be
814 * overridden from expairseq::expandchildren() and done iteratively in order
815 * to allow for early cancallations and thus safe memory.
818 * @return pointer to epvector containing expanded representation or zero
819 * pointer, if sequence is unchanged. */
820 epvector * mul::expandchildren(unsigned options) const
822 const epvector::const_iterator last = seq.end();
823 epvector::const_iterator cit = seq.begin();
825 const ex & factor = recombine_pair_to_ex(*cit);
826 const ex & expanded_factor = factor.expand(options);
827 if (!are_ex_trivially_equal(factor,expanded_factor)) {
829 // something changed, copy seq, eval and return it
830 epvector *s = new epvector;
831 s->reserve(seq.size());
833 // copy parts of seq which are known not to have changed
834 epvector::const_iterator cit2 = seq.begin();
839 // copy first changed element
840 s->push_back(split_ex_to_pair(expanded_factor));
844 s->push_back(split_ex_to_pair(recombine_pair_to_ex(*cit2).expand(options)));
852 return 0; // nothing has changed