3 * Implementation of GiNaC's products of expressions. */
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
31 #include "operators.h"
40 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(mul, expairseq,
41 print_func<print_context>(&mul::do_print).
42 print_func<print_latex>(&mul::do_print_latex).
43 print_func<print_csrc>(&mul::do_print_csrc).
44 print_func<print_tree>(&mul::do_print_tree).
45 print_func<print_python_repr>(&mul::do_print_python_repr))
49 // default constructor
54 tinfo_key = &mul::tinfo_static;
63 mul::mul(const ex & lh, const ex & rh)
65 tinfo_key = &mul::tinfo_static;
67 construct_from_2_ex(lh,rh);
68 GINAC_ASSERT(is_canonical());
71 mul::mul(const exvector & v)
73 tinfo_key = &mul::tinfo_static;
75 construct_from_exvector(v);
76 GINAC_ASSERT(is_canonical());
79 mul::mul(const epvector & v)
81 tinfo_key = &mul::tinfo_static;
83 construct_from_epvector(v);
84 GINAC_ASSERT(is_canonical());
87 mul::mul(const epvector & v, const ex & oc, bool do_index_renaming)
89 tinfo_key = &mul::tinfo_static;
91 construct_from_epvector(v, do_index_renaming);
92 GINAC_ASSERT(is_canonical());
95 mul::mul(std::auto_ptr<epvector> vp, const ex & oc, bool do_index_renaming)
97 tinfo_key = &mul::tinfo_static;
98 GINAC_ASSERT(vp.get()!=0);
100 construct_from_epvector(*vp, do_index_renaming);
101 GINAC_ASSERT(is_canonical());
104 mul::mul(const ex & lh, const ex & mh, const ex & rh)
106 tinfo_key = &mul::tinfo_static;
109 factors.push_back(lh);
110 factors.push_back(mh);
111 factors.push_back(rh);
112 overall_coeff = _ex1;
113 construct_from_exvector(factors);
114 GINAC_ASSERT(is_canonical());
121 DEFAULT_ARCHIVING(mul)
124 // functions overriding virtual functions from base classes
127 void mul::print_overall_coeff(const print_context & c, const char *mul_sym) const
129 const numeric &coeff = ex_to<numeric>(overall_coeff);
130 if (coeff.csgn() == -1)
132 if (!coeff.is_equal(*_num1_p) &&
133 !coeff.is_equal(*_num_1_p)) {
134 if (coeff.is_rational()) {
135 if (coeff.is_negative())
140 if (coeff.csgn() == -1)
141 (-coeff).print(c, precedence());
143 coeff.print(c, precedence());
149 void mul::do_print(const print_context & c, unsigned level) const
151 if (precedence() <= level)
154 print_overall_coeff(c, "*");
156 epvector::const_iterator it = seq.begin(), itend = seq.end();
158 while (it != itend) {
163 recombine_pair_to_ex(*it).print(c, precedence());
167 if (precedence() <= level)
171 void mul::do_print_latex(const print_latex & c, unsigned level) const
173 if (precedence() <= level)
176 print_overall_coeff(c, " ");
178 // Separate factors into those with negative numeric exponent
180 epvector::const_iterator it = seq.begin(), itend = seq.end();
181 exvector neg_powers, others;
182 while (it != itend) {
183 GINAC_ASSERT(is_exactly_a<numeric>(it->coeff));
184 if (ex_to<numeric>(it->coeff).is_negative())
185 neg_powers.push_back(recombine_pair_to_ex(expair(it->rest, -(it->coeff))));
187 others.push_back(recombine_pair_to_ex(*it));
191 if (!neg_powers.empty()) {
193 // Factors with negative exponent are printed as a fraction
195 mul(others).eval().print(c);
197 mul(neg_powers).eval().print(c);
202 // All other factors are printed in the ordinary way
203 exvector::const_iterator vit = others.begin(), vitend = others.end();
204 while (vit != vitend) {
206 vit->print(c, precedence());
211 if (precedence() <= level)
215 void mul::do_print_csrc(const print_csrc & c, unsigned level) const
217 if (precedence() <= level)
220 if (!overall_coeff.is_equal(_ex1)) {
221 if (overall_coeff.is_equal(_ex_1))
224 overall_coeff.print(c, precedence());
229 // Print arguments, separated by "*" or "/"
230 epvector::const_iterator it = seq.begin(), itend = seq.end();
231 while (it != itend) {
233 // If the first argument is a negative integer power, it gets printed as "1.0/<expr>"
234 bool needclosingparenthesis = false;
235 if (it == seq.begin() && it->coeff.info(info_flags::negint)) {
236 if (is_a<print_csrc_cl_N>(c)) {
238 needclosingparenthesis = true;
243 // If the exponent is 1 or -1, it is left out
244 if (it->coeff.is_equal(_ex1) || it->coeff.is_equal(_ex_1))
245 it->rest.print(c, precedence());
246 else if (it->coeff.info(info_flags::negint))
247 // Outer parens around ex needed for broken GCC parser:
248 (ex(power(it->rest, -ex_to<numeric>(it->coeff)))).print(c, level);
250 // Outer parens around ex needed for broken GCC parser:
251 (ex(power(it->rest, ex_to<numeric>(it->coeff)))).print(c, level);
253 if (needclosingparenthesis)
256 // Separator is "/" for negative integer powers, "*" otherwise
259 if (it->coeff.info(info_flags::negint))
266 if (precedence() <= level)
270 void mul::do_print_python_repr(const print_python_repr & c, unsigned level) const
272 c.s << class_name() << '(';
274 for (size_t i=1; i<nops(); ++i) {
281 bool mul::info(unsigned inf) const
284 case info_flags::polynomial:
285 case info_flags::integer_polynomial:
286 case info_flags::cinteger_polynomial:
287 case info_flags::rational_polynomial:
288 case info_flags::crational_polynomial:
289 case info_flags::rational_function: {
290 epvector::const_iterator i = seq.begin(), end = seq.end();
292 if (!(recombine_pair_to_ex(*i).info(inf)))
296 return overall_coeff.info(inf);
298 case info_flags::algebraic: {
299 epvector::const_iterator i = seq.begin(), end = seq.end();
301 if ((recombine_pair_to_ex(*i).info(inf)))
308 return inherited::info(inf);
311 int mul::degree(const ex & s) const
313 // Sum up degrees of factors
315 epvector::const_iterator i = seq.begin(), end = seq.end();
317 if (ex_to<numeric>(i->coeff).is_integer())
318 deg_sum += recombine_pair_to_ex(*i).degree(s);
321 throw std::runtime_error("mul::degree() undefined degree because of non-integer exponent");
328 int mul::ldegree(const ex & s) const
330 // Sum up degrees of factors
332 epvector::const_iterator i = seq.begin(), end = seq.end();
334 if (ex_to<numeric>(i->coeff).is_integer())
335 deg_sum += recombine_pair_to_ex(*i).ldegree(s);
338 throw std::runtime_error("mul::ldegree() undefined degree because of non-integer exponent");
345 ex mul::coeff(const ex & s, int n) const
348 coeffseq.reserve(seq.size()+1);
351 // product of individual coeffs
352 // if a non-zero power of s is found, the resulting product will be 0
353 epvector::const_iterator i = seq.begin(), end = seq.end();
355 coeffseq.push_back(recombine_pair_to_ex(*i).coeff(s,n));
358 coeffseq.push_back(overall_coeff);
359 return (new mul(coeffseq))->setflag(status_flags::dynallocated);
362 epvector::const_iterator i = seq.begin(), end = seq.end();
363 bool coeff_found = false;
365 ex t = recombine_pair_to_ex(*i);
366 ex c = t.coeff(s, n);
368 coeffseq.push_back(c);
371 coeffseq.push_back(t);
376 coeffseq.push_back(overall_coeff);
377 return (new mul(coeffseq))->setflag(status_flags::dynallocated);
383 /** Perform automatic term rewriting rules in this class. In the following
384 * x, x1, x2,... stand for a symbolic variables of type ex and c, c1, c2...
385 * stand for such expressions that contain a plain number.
387 * - *(+(x1,x2,...);c) -> *(+(*(x1,c),*(x2,c),...))
391 * @param level cut-off in recursive evaluation */
392 ex mul::eval(int level) const
394 std::auto_ptr<epvector> evaled_seqp = evalchildren(level);
395 if (evaled_seqp.get()) {
396 // do more evaluation later
397 return (new mul(evaled_seqp, overall_coeff))->
398 setflag(status_flags::dynallocated);
401 #ifdef DO_GINAC_ASSERT
402 epvector::const_iterator i = seq.begin(), end = seq.end();
404 GINAC_ASSERT((!is_exactly_a<mul>(i->rest)) ||
405 (!(ex_to<numeric>(i->coeff).is_integer())));
406 GINAC_ASSERT(!(i->is_canonical_numeric()));
407 if (is_exactly_a<numeric>(recombine_pair_to_ex(*i)))
408 print(print_tree(std::cerr));
409 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*i)));
411 expair p = split_ex_to_pair(recombine_pair_to_ex(*i));
412 GINAC_ASSERT(p.rest.is_equal(i->rest));
413 GINAC_ASSERT(p.coeff.is_equal(i->coeff));
417 #endif // def DO_GINAC_ASSERT
419 if (flags & status_flags::evaluated) {
420 GINAC_ASSERT(seq.size()>0);
421 GINAC_ASSERT(seq.size()>1 || !overall_coeff.is_equal(_ex1));
425 int seq_size = seq.size();
426 if (overall_coeff.is_zero()) {
429 } else if (seq_size==0) {
431 return overall_coeff;
432 } else if (seq_size==1 && overall_coeff.is_equal(_ex1)) {
434 return recombine_pair_to_ex(*(seq.begin()));
435 } else if ((seq_size==1) &&
436 is_exactly_a<add>((*seq.begin()).rest) &&
437 ex_to<numeric>((*seq.begin()).coeff).is_equal(*_num1_p)) {
438 // *(+(x,y,...);c) -> +(*(x,c),*(y,c),...) (c numeric(), no powers of +())
439 const add & addref = ex_to<add>((*seq.begin()).rest);
440 std::auto_ptr<epvector> distrseq(new epvector);
441 distrseq->reserve(addref.seq.size());
442 epvector::const_iterator i = addref.seq.begin(), end = addref.seq.end();
444 distrseq->push_back(addref.combine_pair_with_coeff_to_pair(*i, overall_coeff));
447 return (new add(distrseq,
448 ex_to<numeric>(addref.overall_coeff).
449 mul_dyn(ex_to<numeric>(overall_coeff))))
450 ->setflag(status_flags::dynallocated | status_flags::evaluated);
455 ex mul::evalf(int level) const
458 return mul(seq,overall_coeff);
460 if (level==-max_recursion_level)
461 throw(std::runtime_error("max recursion level reached"));
463 std::auto_ptr<epvector> s(new epvector);
464 s->reserve(seq.size());
467 epvector::const_iterator i = seq.begin(), end = seq.end();
469 s->push_back(combine_ex_with_coeff_to_pair(i->rest.evalf(level),
473 return mul(s, overall_coeff.evalf(level));
476 void mul::find_real_imag(ex & rp, ex & ip) const
478 rp = overall_coeff.real_part();
479 ip = overall_coeff.imag_part();
480 for (epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i) {
481 ex factor = recombine_pair_to_ex(*i);
482 ex new_rp = factor.real_part();
483 ex new_ip = factor.imag_part();
484 if(new_ip.is_zero()) {
488 ex temp = rp*new_rp - ip*new_ip;
489 ip = ip*new_rp + rp*new_ip;
497 ex mul::real_part() const
500 find_real_imag(rp, ip);
504 ex mul::imag_part() const
507 find_real_imag(rp, ip);
511 ex mul::evalm() const
514 if (seq.size() == 1 && seq[0].coeff.is_equal(_ex1)
515 && is_a<matrix>(seq[0].rest))
516 return ex_to<matrix>(seq[0].rest).mul(ex_to<numeric>(overall_coeff));
518 // Evaluate children first, look whether there are any matrices at all
519 // (there can be either no matrices or one matrix; if there were more
520 // than one matrix, it would be a non-commutative product)
521 std::auto_ptr<epvector> s(new epvector);
522 s->reserve(seq.size());
524 bool have_matrix = false;
525 epvector::iterator the_matrix;
527 epvector::const_iterator i = seq.begin(), end = seq.end();
529 const ex &m = recombine_pair_to_ex(*i).evalm();
530 s->push_back(split_ex_to_pair(m));
531 if (is_a<matrix>(m)) {
533 the_matrix = s->end() - 1;
540 // The product contained a matrix. We will multiply all other factors
542 matrix m = ex_to<matrix>(the_matrix->rest);
543 s->erase(the_matrix);
544 ex scalar = (new mul(s, overall_coeff))->setflag(status_flags::dynallocated);
545 return m.mul_scalar(scalar);
548 return (new mul(s, overall_coeff))->setflag(status_flags::dynallocated);
551 ex mul::eval_ncmul(const exvector & v) const
554 return inherited::eval_ncmul(v);
556 // Find first noncommutative element and call its eval_ncmul()
557 epvector::const_iterator i = seq.begin(), end = seq.end();
559 if (i->rest.return_type() == return_types::noncommutative)
560 return i->rest.eval_ncmul(v);
563 return inherited::eval_ncmul(v);
566 bool tryfactsubs(const ex & origfactor, const ex & patternfactor, int & nummatches, lst & repls)
572 if (is_exactly_a<power>(origfactor) && origfactor.op(1).info(info_flags::integer)) {
573 origbase = origfactor.op(0);
574 int expon = ex_to<numeric>(origfactor.op(1)).to_int();
575 origexponent = expon > 0 ? expon : -expon;
576 origexpsign = expon > 0 ? 1 : -1;
578 origbase = origfactor;
587 if (is_exactly_a<power>(patternfactor) && patternfactor.op(1).info(info_flags::integer)) {
588 patternbase = patternfactor.op(0);
589 int expon = ex_to<numeric>(patternfactor.op(1)).to_int();
590 patternexponent = expon > 0 ? expon : -expon;
591 patternexpsign = expon > 0 ? 1 : -1;
593 patternbase = patternfactor;
598 lst saverepls = repls;
599 if (origexponent < patternexponent || origexpsign != patternexpsign || !origbase.match(patternbase,saverepls))
603 int newnummatches = origexponent / patternexponent;
604 if (newnummatches < nummatches)
605 nummatches = newnummatches;
609 /** Checks wheter e matches to the pattern pat and the (possibly to be updated)
610 * list of replacements repls. This matching is in the sense of algebraic
611 * substitutions. Matching starts with pat.op(factor) of the pattern because
612 * the factors before this one have already been matched. The (possibly
613 * updated) number of matches is in nummatches. subsed[i] is true for factors
614 * that already have been replaced by previous substitutions and matched[i]
615 * is true for factors that have been matched by the current match.
617 bool algebraic_match_mul_with_mul(const mul &e, const ex &pat, lst &repls,
618 int factor, int &nummatches, const std::vector<bool> &subsed,
619 std::vector<bool> &matched)
621 if (factor == pat.nops())
624 for (size_t i=0; i<e.nops(); ++i) {
625 if(subsed[i] || matched[i])
627 lst newrepls = repls;
628 int newnummatches = nummatches;
629 if (tryfactsubs(e.op(i), pat.op(factor), newnummatches, newrepls)) {
631 if (algebraic_match_mul_with_mul(e, pat, newrepls, factor+1,
632 newnummatches, subsed, matched)) {
634 nummatches = newnummatches;
645 bool mul::has(const ex & pattern, unsigned options) const
647 if(!(options&has_options::algebraic))
648 return basic::has(pattern,options);
649 if(is_a<mul>(pattern)) {
651 int nummatches = std::numeric_limits<int>::max();
652 std::vector<bool> subsed(seq.size(), false);
653 std::vector<bool> matched(seq.size(), false);
654 if(algebraic_match_mul_with_mul(*this, pattern, repls, 0, nummatches,
658 return basic::has(pattern, options);
661 ex mul::algebraic_subs_mul(const exmap & m, unsigned options) const
663 std::vector<bool> subsed(seq.size(), false);
664 exvector subsresult(seq.size());
668 for (exmap::const_iterator it = m.begin(); it != m.end(); ++it) {
670 if (is_exactly_a<mul>(it->first)) {
672 int nummatches = std::numeric_limits<int>::max();
673 std::vector<bool> currsubsed(seq.size(), false);
676 if(!algebraic_match_mul_with_mul(*this, it->first, repls, 0, nummatches, subsed, currsubsed))
679 for (size_t j=0; j<subsed.size(); j++)
683 = it->first.subs(ex(repls), subs_options::no_pattern);
684 divide_by *= power(subsed_pattern, nummatches);
686 = it->second.subs(ex(repls), subs_options::no_pattern);
687 multiply_by *= power(subsed_result, nummatches);
692 for (size_t j=0; j<this->nops(); j++) {
693 int nummatches = std::numeric_limits<int>::max();
695 if (!subsed[j] && tryfactsubs(op(j), it->first, nummatches, repls)){
698 = it->first.subs(ex(repls), subs_options::no_pattern);
699 divide_by *= power(subsed_pattern, nummatches);
701 = it->second.subs(ex(repls), subs_options::no_pattern);
702 multiply_by *= power(subsed_result, nummatches);
708 bool subsfound = false;
709 for (size_t i=0; i<subsed.size(); i++) {
716 return subs_one_level(m, options | subs_options::algebraic);
718 return ((*this)/divide_by)*multiply_by;
723 /** Implementation of ex::diff() for a product. It applies the product rule.
725 ex mul::derivative(const symbol & s) const
727 size_t num = seq.size();
731 // D(a*b*c) = D(a)*b*c + a*D(b)*c + a*b*D(c)
732 epvector mulseq = seq;
733 epvector::const_iterator i = seq.begin(), end = seq.end();
734 epvector::iterator i2 = mulseq.begin();
736 expair ep = split_ex_to_pair(power(i->rest, i->coeff - _ex1) *
739 addseq.push_back((new mul(mulseq, overall_coeff * i->coeff))->setflag(status_flags::dynallocated));
743 return (new add(addseq))->setflag(status_flags::dynallocated);
746 int mul::compare_same_type(const basic & other) const
748 return inherited::compare_same_type(other);
751 unsigned mul::return_type() const
754 // mul without factors: should not happen, but commutates
755 return return_types::commutative;
758 bool all_commutative = true;
759 epvector::const_iterator noncommutative_element; // point to first found nc element
761 epvector::const_iterator i = seq.begin(), end = seq.end();
763 unsigned rt = i->rest.return_type();
764 if (rt == return_types::noncommutative_composite)
765 return rt; // one ncc -> mul also ncc
766 if ((rt == return_types::noncommutative) && (all_commutative)) {
767 // first nc element found, remember position
768 noncommutative_element = i;
769 all_commutative = false;
771 if ((rt == return_types::noncommutative) && (!all_commutative)) {
772 // another nc element found, compare type_infos
773 if (noncommutative_element->rest.return_type_tinfo() != i->rest.return_type_tinfo()) {
774 // different types -> mul is ncc
775 return return_types::noncommutative_composite;
780 // all factors checked
781 return all_commutative ? return_types::commutative : return_types::noncommutative;
784 tinfo_t mul::return_type_tinfo() const
787 return this; // mul without factors: should not happen
789 // return type_info of first noncommutative element
790 epvector::const_iterator i = seq.begin(), end = seq.end();
792 if (i->rest.return_type() == return_types::noncommutative)
793 return i->rest.return_type_tinfo();
796 // no noncommutative element found, should not happen
800 ex mul::thisexpairseq(const epvector & v, const ex & oc, bool do_index_renaming) const
802 return (new mul(v, oc, do_index_renaming))->setflag(status_flags::dynallocated);
805 ex mul::thisexpairseq(std::auto_ptr<epvector> vp, const ex & oc, bool do_index_renaming) const
807 return (new mul(vp, oc, do_index_renaming))->setflag(status_flags::dynallocated);
810 expair mul::split_ex_to_pair(const ex & e) const
812 if (is_exactly_a<power>(e)) {
813 const power & powerref = ex_to<power>(e);
814 if (is_exactly_a<numeric>(powerref.exponent))
815 return expair(powerref.basis,powerref.exponent);
817 return expair(e,_ex1);
820 expair mul::combine_ex_with_coeff_to_pair(const ex & e,
823 // to avoid duplication of power simplification rules,
824 // we create a temporary power object
825 // otherwise it would be hard to correctly evaluate
826 // expression like (4^(1/3))^(3/2)
827 if (c.is_equal(_ex1))
828 return split_ex_to_pair(e);
830 return split_ex_to_pair(power(e,c));
833 expair mul::combine_pair_with_coeff_to_pair(const expair & p,
836 // to avoid duplication of power simplification rules,
837 // we create a temporary power object
838 // otherwise it would be hard to correctly evaluate
839 // expression like (4^(1/3))^(3/2)
840 if (c.is_equal(_ex1))
843 return split_ex_to_pair(power(recombine_pair_to_ex(p),c));
846 ex mul::recombine_pair_to_ex(const expair & p) const
848 if (ex_to<numeric>(p.coeff).is_equal(*_num1_p))
851 return (new power(p.rest,p.coeff))->setflag(status_flags::dynallocated);
854 bool mul::expair_needs_further_processing(epp it)
856 if (is_exactly_a<mul>(it->rest) &&
857 ex_to<numeric>(it->coeff).is_integer()) {
858 // combined pair is product with integer power -> expand it
859 *it = split_ex_to_pair(recombine_pair_to_ex(*it));
862 if (is_exactly_a<numeric>(it->rest)) {
863 expair ep = split_ex_to_pair(recombine_pair_to_ex(*it));
864 if (!ep.is_equal(*it)) {
865 // combined pair is a numeric power which can be simplified
869 if (it->coeff.is_equal(_ex1)) {
870 // combined pair has coeff 1 and must be moved to the end
877 ex mul::default_overall_coeff() const
882 void mul::combine_overall_coeff(const ex & c)
884 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
885 GINAC_ASSERT(is_exactly_a<numeric>(c));
886 overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c));
889 void mul::combine_overall_coeff(const ex & c1, const ex & c2)
891 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
892 GINAC_ASSERT(is_exactly_a<numeric>(c1));
893 GINAC_ASSERT(is_exactly_a<numeric>(c2));
894 overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c1).power(ex_to<numeric>(c2)));
897 bool mul::can_make_flat(const expair & p) const
899 GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
900 // this assertion will probably fail somewhere
901 // it would require a more careful make_flat, obeying the power laws
902 // probably should return true only if p.coeff is integer
903 return ex_to<numeric>(p.coeff).is_equal(*_num1_p);
906 bool mul::can_be_further_expanded(const ex & e)
908 if (is_exactly_a<mul>(e)) {
909 for (epvector::const_iterator cit = ex_to<mul>(e).seq.begin(); cit != ex_to<mul>(e).seq.end(); ++cit) {
910 if (is_exactly_a<add>(cit->rest) && cit->coeff.info(info_flags::posint))
913 } else if (is_exactly_a<power>(e)) {
914 if (is_exactly_a<add>(e.op(0)) && e.op(1).info(info_flags::posint))
920 ex mul::expand(unsigned options) const
922 // First, expand the children
923 std::auto_ptr<epvector> expanded_seqp = expandchildren(options);
924 const epvector & expanded_seq = (expanded_seqp.get() ? *expanded_seqp : seq);
926 // Now, look for all the factors that are sums and multiply each one out
927 // with the next one that is found while collecting the factors which are
929 ex last_expanded = _ex1;
932 non_adds.reserve(expanded_seq.size());
934 for (epvector::const_iterator cit = expanded_seq.begin(); cit != expanded_seq.end(); ++cit) {
935 if (is_exactly_a<add>(cit->rest) &&
936 (cit->coeff.is_equal(_ex1))) {
937 if (is_exactly_a<add>(last_expanded)) {
939 // Expand a product of two sums, aggressive version.
940 // Caring for the overall coefficients in separate loops can
941 // sometimes give a performance gain of up to 15%!
943 const int sizedifference = ex_to<add>(last_expanded).seq.size()-ex_to<add>(cit->rest).seq.size();
944 // add2 is for the inner loop and should be the bigger of the two sums
945 // in the presence of asymptotically good sorting:
946 const add& add1 = (sizedifference<0 ? ex_to<add>(last_expanded) : ex_to<add>(cit->rest));
947 const add& add2 = (sizedifference<0 ? ex_to<add>(cit->rest) : ex_to<add>(last_expanded));
948 const epvector::const_iterator add1begin = add1.seq.begin();
949 const epvector::const_iterator add1end = add1.seq.end();
950 const epvector::const_iterator add2begin = add2.seq.begin();
951 const epvector::const_iterator add2end = add2.seq.end();
953 distrseq.reserve(add1.seq.size()+add2.seq.size());
955 // Multiply add2 with the overall coefficient of add1 and append it to distrseq:
956 if (!add1.overall_coeff.is_zero()) {
957 if (add1.overall_coeff.is_equal(_ex1))
958 distrseq.insert(distrseq.end(),add2begin,add2end);
960 for (epvector::const_iterator i=add2begin; i!=add2end; ++i)
961 distrseq.push_back(expair(i->rest, ex_to<numeric>(i->coeff).mul_dyn(ex_to<numeric>(add1.overall_coeff))));
964 // Multiply add1 with the overall coefficient of add2 and append it to distrseq:
965 if (!add2.overall_coeff.is_zero()) {
966 if (add2.overall_coeff.is_equal(_ex1))
967 distrseq.insert(distrseq.end(),add1begin,add1end);
969 for (epvector::const_iterator i=add1begin; i!=add1end; ++i)
970 distrseq.push_back(expair(i->rest, ex_to<numeric>(i->coeff).mul_dyn(ex_to<numeric>(add2.overall_coeff))));
973 // Compute the new overall coefficient and put it together:
974 ex tmp_accu = (new add(distrseq, add1.overall_coeff*add2.overall_coeff))->setflag(status_flags::dynallocated);
976 exvector add1_dummy_indices, add2_dummy_indices, add_indices;
978 for (epvector::const_iterator i=add1begin; i!=add1end; ++i) {
979 add_indices = get_all_dummy_indices_safely(i->rest);
980 add1_dummy_indices.insert(add1_dummy_indices.end(), add_indices.begin(), add_indices.end());
982 for (epvector::const_iterator i=add2begin; i!=add2end; ++i) {
983 add_indices = get_all_dummy_indices_safely(i->rest);
984 add2_dummy_indices.insert(add2_dummy_indices.end(), add_indices.begin(), add_indices.end());
987 sort(add1_dummy_indices.begin(), add1_dummy_indices.end(), ex_is_less());
988 sort(add2_dummy_indices.begin(), add2_dummy_indices.end(), ex_is_less());
989 lst dummy_subs = rename_dummy_indices_uniquely(add1_dummy_indices, add2_dummy_indices);
991 // Multiply explicitly all non-numeric terms of add1 and add2:
992 for (epvector::const_iterator i2=add2begin; i2!=add2end; ++i2) {
993 // We really have to combine terms here in order to compactify
994 // the result. Otherwise it would become waayy tooo bigg.
997 ex i2_new = (dummy_subs.op(0).nops()>0?
998 i2->rest.subs((lst)dummy_subs.op(0), (lst)dummy_subs.op(1), subs_options::no_pattern) : i2->rest);
999 for (epvector::const_iterator i1=add1begin; i1!=add1end; ++i1) {
1000 // Don't push_back expairs which might have a rest that evaluates to a numeric,
1001 // since that would violate an invariant of expairseq:
1002 const ex rest = (new mul(i1->rest, i2_new))->setflag(status_flags::dynallocated);
1003 if (is_exactly_a<numeric>(rest)) {
1004 oc += ex_to<numeric>(rest).mul(ex_to<numeric>(i1->coeff).mul(ex_to<numeric>(i2->coeff)));
1006 distrseq.push_back(expair(rest, ex_to<numeric>(i1->coeff).mul_dyn(ex_to<numeric>(i2->coeff))));
1009 tmp_accu += (new add(distrseq, oc))->setflag(status_flags::dynallocated);
1011 last_expanded = tmp_accu;
1014 if (!last_expanded.is_equal(_ex1))
1015 non_adds.push_back(split_ex_to_pair(last_expanded));
1016 last_expanded = cit->rest;
1020 non_adds.push_back(*cit);
1024 // Now the only remaining thing to do is to multiply the factors which
1025 // were not sums into the "last_expanded" sum
1026 if (is_exactly_a<add>(last_expanded)) {
1027 size_t n = last_expanded.nops();
1029 distrseq.reserve(n);
1030 exvector va = get_all_dummy_indices_safely(mul(non_adds));
1031 sort(va.begin(), va.end(), ex_is_less());
1033 for (size_t i=0; i<n; ++i) {
1034 epvector factors = non_adds;
1035 factors.push_back(split_ex_to_pair(rename_dummy_indices_uniquely(va, last_expanded.op(i))));
1036 ex term = (new mul(factors, overall_coeff))->setflag(status_flags::dynallocated);
1037 if (can_be_further_expanded(term)) {
1038 distrseq.push_back(term.expand());
1041 ex_to<basic>(term).setflag(status_flags::expanded);
1042 distrseq.push_back(term);
1046 return ((new add(distrseq))->
1047 setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0)));
1050 non_adds.push_back(split_ex_to_pair(last_expanded));
1051 ex result = (new mul(non_adds, overall_coeff))->setflag(status_flags::dynallocated);
1052 if (can_be_further_expanded(result)) {
1053 return result.expand();
1056 ex_to<basic>(result).setflag(status_flags::expanded);
1063 // new virtual functions which can be overridden by derived classes
1069 // non-virtual functions in this class
1073 /** Member-wise expand the expairs representing this sequence. This must be
1074 * overridden from expairseq::expandchildren() and done iteratively in order
1075 * to allow for early cancallations and thus safe memory.
1077 * @see mul::expand()
1078 * @return pointer to epvector containing expanded representation or zero
1079 * pointer, if sequence is unchanged. */
1080 std::auto_ptr<epvector> mul::expandchildren(unsigned options) const
1082 const epvector::const_iterator last = seq.end();
1083 epvector::const_iterator cit = seq.begin();
1085 const ex & factor = recombine_pair_to_ex(*cit);
1086 const ex & expanded_factor = factor.expand(options);
1087 if (!are_ex_trivially_equal(factor,expanded_factor)) {
1089 // something changed, copy seq, eval and return it
1090 std::auto_ptr<epvector> s(new epvector);
1091 s->reserve(seq.size());
1093 // copy parts of seq which are known not to have changed
1094 epvector::const_iterator cit2 = seq.begin();
1096 s->push_back(*cit2);
1100 // copy first changed element
1101 s->push_back(split_ex_to_pair(expanded_factor));
1105 while (cit2!=last) {
1106 s->push_back(split_ex_to_pair(recombine_pair_to_ex(*cit2).expand(options)));
1114 return std::auto_ptr<epvector>(0); // nothing has changed
1117 } // namespace GiNaC