3 * Implementation of GiNaC's products of expressions. */
6 * GiNaC Copyright (C) 1999-2006 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)
89 tinfo_key = &mul::tinfo_static;
91 construct_from_epvector(v);
92 GINAC_ASSERT(is_canonical());
95 mul::mul(std::auto_ptr<epvector> vp, const ex & oc)
97 tinfo_key = &mul::tinfo_static;
98 GINAC_ASSERT(vp.get()!=0);
100 construct_from_epvector(*vp);
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 overall_coeff.print(c, precedence());
225 // Print arguments, separated by "*" or "/"
226 epvector::const_iterator it = seq.begin(), itend = seq.end();
227 while (it != itend) {
229 // If the first argument is a negative integer power, it gets printed as "1.0/<expr>"
230 bool needclosingparenthesis = false;
231 if (it == seq.begin() && it->coeff.info(info_flags::negint)) {
232 if (is_a<print_csrc_cl_N>(c)) {
234 needclosingparenthesis = true;
239 // If the exponent is 1 or -1, it is left out
240 if (it->coeff.is_equal(_ex1) || it->coeff.is_equal(_ex_1))
241 it->rest.print(c, precedence());
242 else if (it->coeff.info(info_flags::negint))
243 // Outer parens around ex needed for broken GCC parser:
244 (ex(power(it->rest, -ex_to<numeric>(it->coeff)))).print(c, level);
246 // Outer parens around ex needed for broken GCC parser:
247 (ex(power(it->rest, ex_to<numeric>(it->coeff)))).print(c, level);
249 if (needclosingparenthesis)
252 // Separator is "/" for negative integer powers, "*" otherwise
255 if (it->coeff.info(info_flags::negint))
262 if (precedence() <= level)
266 void mul::do_print_python_repr(const print_python_repr & c, unsigned level) const
268 c.s << class_name() << '(';
270 for (size_t i=1; i<nops(); ++i) {
277 bool mul::info(unsigned inf) const
280 case info_flags::polynomial:
281 case info_flags::integer_polynomial:
282 case info_flags::cinteger_polynomial:
283 case info_flags::rational_polynomial:
284 case info_flags::crational_polynomial:
285 case info_flags::rational_function: {
286 epvector::const_iterator i = seq.begin(), end = seq.end();
288 if (!(recombine_pair_to_ex(*i).info(inf)))
292 return overall_coeff.info(inf);
294 case info_flags::algebraic: {
295 epvector::const_iterator i = seq.begin(), end = seq.end();
297 if ((recombine_pair_to_ex(*i).info(inf)))
304 return inherited::info(inf);
307 int mul::degree(const ex & s) const
309 // Sum up degrees of factors
311 epvector::const_iterator i = seq.begin(), end = seq.end();
313 if (ex_to<numeric>(i->coeff).is_integer())
314 deg_sum += i->rest.degree(s) * ex_to<numeric>(i->coeff).to_int();
320 int mul::ldegree(const ex & s) const
322 // Sum up degrees of factors
324 epvector::const_iterator i = seq.begin(), end = seq.end();
326 if (ex_to<numeric>(i->coeff).is_integer())
327 deg_sum += i->rest.ldegree(s) * ex_to<numeric>(i->coeff).to_int();
333 ex mul::coeff(const ex & s, int n) const
336 coeffseq.reserve(seq.size()+1);
339 // product of individual coeffs
340 // if a non-zero power of s is found, the resulting product will be 0
341 epvector::const_iterator i = seq.begin(), end = seq.end();
343 coeffseq.push_back(recombine_pair_to_ex(*i).coeff(s,n));
346 coeffseq.push_back(overall_coeff);
347 return (new mul(coeffseq))->setflag(status_flags::dynallocated);
350 epvector::const_iterator i = seq.begin(), end = seq.end();
351 bool coeff_found = false;
353 ex t = recombine_pair_to_ex(*i);
354 ex c = t.coeff(s, n);
356 coeffseq.push_back(c);
359 coeffseq.push_back(t);
364 coeffseq.push_back(overall_coeff);
365 return (new mul(coeffseq))->setflag(status_flags::dynallocated);
371 /** Perform automatic term rewriting rules in this class. In the following
372 * x, x1, x2,... stand for a symbolic variables of type ex and c, c1, c2...
373 * stand for such expressions that contain a plain number.
375 * - *(+(x1,x2,...);c) -> *(+(*(x1,c),*(x2,c),...))
379 * @param level cut-off in recursive evaluation */
380 ex mul::eval(int level) const
382 std::auto_ptr<epvector> evaled_seqp = evalchildren(level);
383 if (evaled_seqp.get()) {
384 // do more evaluation later
385 return (new mul(evaled_seqp, overall_coeff))->
386 setflag(status_flags::dynallocated);
389 #ifdef DO_GINAC_ASSERT
390 epvector::const_iterator i = seq.begin(), end = seq.end();
392 GINAC_ASSERT((!is_exactly_a<mul>(i->rest)) ||
393 (!(ex_to<numeric>(i->coeff).is_integer())));
394 GINAC_ASSERT(!(i->is_canonical_numeric()));
395 if (is_exactly_a<numeric>(recombine_pair_to_ex(*i)))
396 print(print_tree(std::cerr));
397 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*i)));
399 expair p = split_ex_to_pair(recombine_pair_to_ex(*i));
400 GINAC_ASSERT(p.rest.is_equal(i->rest));
401 GINAC_ASSERT(p.coeff.is_equal(i->coeff));
405 #endif // def DO_GINAC_ASSERT
407 if (flags & status_flags::evaluated) {
408 GINAC_ASSERT(seq.size()>0);
409 GINAC_ASSERT(seq.size()>1 || !overall_coeff.is_equal(_ex1));
413 int seq_size = seq.size();
414 if (overall_coeff.is_zero()) {
417 } else if (seq_size==0) {
419 return overall_coeff;
420 } else if (seq_size==1 && overall_coeff.is_equal(_ex1)) {
422 return recombine_pair_to_ex(*(seq.begin()));
423 } else if ((seq_size==1) &&
424 is_exactly_a<add>((*seq.begin()).rest) &&
425 ex_to<numeric>((*seq.begin()).coeff).is_equal(*_num1_p)) {
426 // *(+(x,y,...);c) -> +(*(x,c),*(y,c),...) (c numeric(), no powers of +())
427 const add & addref = ex_to<add>((*seq.begin()).rest);
428 std::auto_ptr<epvector> distrseq(new epvector);
429 distrseq->reserve(addref.seq.size());
430 epvector::const_iterator i = addref.seq.begin(), end = addref.seq.end();
432 distrseq->push_back(addref.combine_pair_with_coeff_to_pair(*i, overall_coeff));
435 return (new add(distrseq,
436 ex_to<numeric>(addref.overall_coeff).
437 mul_dyn(ex_to<numeric>(overall_coeff))))
438 ->setflag(status_flags::dynallocated | status_flags::evaluated);
443 ex mul::evalf(int level) const
446 return mul(seq,overall_coeff);
448 if (level==-max_recursion_level)
449 throw(std::runtime_error("max recursion level reached"));
451 std::auto_ptr<epvector> s(new epvector);
452 s->reserve(seq.size());
455 epvector::const_iterator i = seq.begin(), end = seq.end();
457 s->push_back(combine_ex_with_coeff_to_pair(i->rest.evalf(level),
461 return mul(s, overall_coeff.evalf(level));
464 void mul::find_real_imag(ex & rp, ex & ip) const
466 rp = overall_coeff.real_part();
467 ip = overall_coeff.imag_part();
468 for (epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i) {
469 ex factor = recombine_pair_to_ex(*i);
470 ex new_rp = factor.real_part();
471 ex new_ip = factor.imag_part();
472 if(new_ip.is_zero()) {
476 ex temp = rp*new_rp - ip*new_ip;
477 ip = ip*new_rp + rp*new_ip;
485 ex mul::real_part() const
488 find_real_imag(rp, ip);
492 ex mul::imag_part() const
495 find_real_imag(rp, ip);
499 ex mul::evalm() const
502 if (seq.size() == 1 && seq[0].coeff.is_equal(_ex1)
503 && is_a<matrix>(seq[0].rest))
504 return ex_to<matrix>(seq[0].rest).mul(ex_to<numeric>(overall_coeff));
506 // Evaluate children first, look whether there are any matrices at all
507 // (there can be either no matrices or one matrix; if there were more
508 // than one matrix, it would be a non-commutative product)
509 std::auto_ptr<epvector> s(new epvector);
510 s->reserve(seq.size());
512 bool have_matrix = false;
513 epvector::iterator the_matrix;
515 epvector::const_iterator i = seq.begin(), end = seq.end();
517 const ex &m = recombine_pair_to_ex(*i).evalm();
518 s->push_back(split_ex_to_pair(m));
519 if (is_a<matrix>(m)) {
521 the_matrix = s->end() - 1;
528 // The product contained a matrix. We will multiply all other factors
530 matrix m = ex_to<matrix>(the_matrix->rest);
531 s->erase(the_matrix);
532 ex scalar = (new mul(s, overall_coeff))->setflag(status_flags::dynallocated);
533 return m.mul_scalar(scalar);
536 return (new mul(s, overall_coeff))->setflag(status_flags::dynallocated);
539 ex mul::eval_ncmul(const exvector & v) const
542 return inherited::eval_ncmul(v);
544 // Find first noncommutative element and call its eval_ncmul()
545 epvector::const_iterator i = seq.begin(), end = seq.end();
547 if (i->rest.return_type() == return_types::noncommutative)
548 return i->rest.eval_ncmul(v);
551 return inherited::eval_ncmul(v);
554 bool tryfactsubs(const ex & origfactor, const ex & patternfactor, int & nummatches, lst & repls)
560 if (is_exactly_a<power>(origfactor) && origfactor.op(1).info(info_flags::integer)) {
561 origbase = origfactor.op(0);
562 int expon = ex_to<numeric>(origfactor.op(1)).to_int();
563 origexponent = expon > 0 ? expon : -expon;
564 origexpsign = expon > 0 ? 1 : -1;
566 origbase = origfactor;
575 if (is_exactly_a<power>(patternfactor) && patternfactor.op(1).info(info_flags::integer)) {
576 patternbase = patternfactor.op(0);
577 int expon = ex_to<numeric>(patternfactor.op(1)).to_int();
578 patternexponent = expon > 0 ? expon : -expon;
579 patternexpsign = expon > 0 ? 1 : -1;
581 patternbase = patternfactor;
586 lst saverepls = repls;
587 if (origexponent < patternexponent || origexpsign != patternexpsign || !origbase.match(patternbase,saverepls))
591 int newnummatches = origexponent / patternexponent;
592 if (newnummatches < nummatches)
593 nummatches = newnummatches;
597 /** Checks wheter e matches to the pattern pat and the (possibly to be updated
598 * list of replacements repls. This matching is in the sense of algebraic
599 * substitutions. Matching starts with pat.op(factor) of the pattern because
600 * the factors before this one have already been matched. The (possibly
601 * updated) number of matches is in nummatches. subsed[i] is true for factors
602 * that already have been replaced by previous substitutions and matched[i]
603 * is true for factors that have been matched by the current match.
605 bool algebraic_match_mul_with_mul(const mul &e, const ex &pat, lst &repls,
606 int factor, int &nummatches, const std::vector<bool> &subsed,
607 std::vector<bool> &matched)
609 if (factor == pat.nops())
612 for (size_t i=0; i<e.nops(); ++i) {
613 if(subsed[i] || matched[i])
615 lst newrepls = repls;
616 int newnummatches = nummatches;
617 if (tryfactsubs(e.op(i), pat.op(factor), newnummatches, newrepls)) {
619 if (algebraic_match_mul_with_mul(e, pat, newrepls, factor+1,
620 newnummatches, subsed, matched)) {
622 nummatches = newnummatches;
633 bool mul::has(const ex & pattern, unsigned options) const
635 if(!(options&has_options::algebraic))
636 return basic::has(pattern,options);
637 if(is_a<mul>(pattern)) {
639 int nummatches = std::numeric_limits<int>::max();
640 std::vector<bool> subsed(seq.size(), false);
641 std::vector<bool> matched(seq.size(), false);
642 if(algebraic_match_mul_with_mul(*this, pattern, repls, 0, nummatches,
646 return basic::has(pattern, options);
649 ex mul::algebraic_subs_mul(const exmap & m, unsigned options) const
651 std::vector<bool> subsed(seq.size(), false);
652 exvector subsresult(seq.size());
654 for (exmap::const_iterator it = m.begin(); it != m.end(); ++it) {
656 if (is_exactly_a<mul>(it->first)) {
658 int nummatches = std::numeric_limits<int>::max();
659 std::vector<bool> currsubsed(seq.size(), false);
663 if(!algebraic_match_mul_with_mul(*this, it->first, repls, 0, nummatches, subsed, currsubsed))
666 bool foundfirstsubsedfactor = false;
667 for (size_t j=0; j<subsed.size(); j++) {
669 if (foundfirstsubsedfactor)
670 subsresult[j] = op(j);
672 foundfirstsubsedfactor = true;
673 subsresult[j] = op(j) * power(it->second.subs(ex(repls), subs_options::no_pattern) / it->first.subs(ex(repls), subs_options::no_pattern), nummatches);
682 int nummatches = std::numeric_limits<int>::max();
685 for (size_t j=0; j<this->nops(); j++) {
686 if (!subsed[j] && tryfactsubs(op(j), it->first, nummatches, repls)) {
688 subsresult[j] = op(j) * power(it->second.subs(ex(repls), subs_options::no_pattern) / it->first.subs(ex(repls), subs_options::no_pattern), nummatches);
695 bool subsfound = false;
696 for (size_t i=0; i<subsed.size(); i++) {
703 return subs_one_level(m, options | subs_options::algebraic);
705 exvector ev; ev.reserve(nops());
706 for (size_t i=0; i<nops(); i++) {
708 ev.push_back(subsresult[i]);
713 return (new mul(ev))->setflag(status_flags::dynallocated);
718 /** Implementation of ex::diff() for a product. It applies the product rule.
720 ex mul::derivative(const symbol & s) const
722 size_t num = seq.size();
726 // D(a*b*c) = D(a)*b*c + a*D(b)*c + a*b*D(c)
727 epvector mulseq = seq;
728 epvector::const_iterator i = seq.begin(), end = seq.end();
729 epvector::iterator i2 = mulseq.begin();
731 expair ep = split_ex_to_pair(power(i->rest, i->coeff - _ex1) *
734 addseq.push_back((new mul(mulseq, overall_coeff * i->coeff))->setflag(status_flags::dynallocated));
738 return (new add(addseq))->setflag(status_flags::dynallocated);
741 int mul::compare_same_type(const basic & other) const
743 return inherited::compare_same_type(other);
746 unsigned mul::return_type() const
749 // mul without factors: should not happen, but commutates
750 return return_types::commutative;
753 bool all_commutative = true;
754 epvector::const_iterator noncommutative_element; // point to first found nc element
756 epvector::const_iterator i = seq.begin(), end = seq.end();
758 unsigned rt = i->rest.return_type();
759 if (rt == return_types::noncommutative_composite)
760 return rt; // one ncc -> mul also ncc
761 if ((rt == return_types::noncommutative) && (all_commutative)) {
762 // first nc element found, remember position
763 noncommutative_element = i;
764 all_commutative = false;
766 if ((rt == return_types::noncommutative) && (!all_commutative)) {
767 // another nc element found, compare type_infos
768 if (noncommutative_element->rest.return_type_tinfo() != i->rest.return_type_tinfo()) {
769 // different types -> mul is ncc
770 return return_types::noncommutative_composite;
775 // all factors checked
776 return all_commutative ? return_types::commutative : return_types::noncommutative;
779 tinfo_t mul::return_type_tinfo() const
782 return this; // mul without factors: should not happen
784 // return type_info of first noncommutative element
785 epvector::const_iterator i = seq.begin(), end = seq.end();
787 if (i->rest.return_type() == return_types::noncommutative)
788 return i->rest.return_type_tinfo();
791 // no noncommutative element found, should not happen
795 ex mul::thisexpairseq(const epvector & v, const ex & oc) const
797 return (new mul(v, oc))->setflag(status_flags::dynallocated);
800 ex mul::thisexpairseq(std::auto_ptr<epvector> vp, const ex & oc) const
802 return (new mul(vp, oc))->setflag(status_flags::dynallocated);
805 expair mul::split_ex_to_pair(const ex & e) const
807 if (is_exactly_a<power>(e)) {
808 const power & powerref = ex_to<power>(e);
809 if (is_exactly_a<numeric>(powerref.exponent))
810 return expair(powerref.basis,powerref.exponent);
812 return expair(e,_ex1);
815 expair mul::combine_ex_with_coeff_to_pair(const ex & e,
818 // to avoid duplication of power simplification rules,
819 // we create a temporary power object
820 // otherwise it would be hard to correctly evaluate
821 // expression like (4^(1/3))^(3/2)
822 if (c.is_equal(_ex1))
823 return split_ex_to_pair(e);
825 return split_ex_to_pair(power(e,c));
828 expair mul::combine_pair_with_coeff_to_pair(const expair & p,
831 // to avoid duplication of power simplification rules,
832 // we create a temporary power object
833 // otherwise it would be hard to correctly evaluate
834 // expression like (4^(1/3))^(3/2)
835 if (c.is_equal(_ex1))
838 return split_ex_to_pair(power(recombine_pair_to_ex(p),c));
841 ex mul::recombine_pair_to_ex(const expair & p) const
843 if (ex_to<numeric>(p.coeff).is_equal(*_num1_p))
846 return (new power(p.rest,p.coeff))->setflag(status_flags::dynallocated);
849 bool mul::expair_needs_further_processing(epp it)
851 if (is_exactly_a<mul>(it->rest) &&
852 ex_to<numeric>(it->coeff).is_integer()) {
853 // combined pair is product with integer power -> expand it
854 *it = split_ex_to_pair(recombine_pair_to_ex(*it));
857 if (is_exactly_a<numeric>(it->rest)) {
858 expair ep = split_ex_to_pair(recombine_pair_to_ex(*it));
859 if (!ep.is_equal(*it)) {
860 // combined pair is a numeric power which can be simplified
864 if (it->coeff.is_equal(_ex1)) {
865 // combined pair has coeff 1 and must be moved to the end
872 ex mul::default_overall_coeff() const
877 void mul::combine_overall_coeff(const ex & c)
879 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
880 GINAC_ASSERT(is_exactly_a<numeric>(c));
881 overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c));
884 void mul::combine_overall_coeff(const ex & c1, const ex & c2)
886 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
887 GINAC_ASSERT(is_exactly_a<numeric>(c1));
888 GINAC_ASSERT(is_exactly_a<numeric>(c2));
889 overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c1).power(ex_to<numeric>(c2)));
892 bool mul::can_make_flat(const expair & p) const
894 GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
895 // this assertion will probably fail somewhere
896 // it would require a more careful make_flat, obeying the power laws
897 // probably should return true only if p.coeff is integer
898 return ex_to<numeric>(p.coeff).is_equal(*_num1_p);
901 bool mul::can_be_further_expanded(const ex & e)
903 if (is_exactly_a<mul>(e)) {
904 for (epvector::const_iterator cit = ex_to<mul>(e).seq.begin(); cit != ex_to<mul>(e).seq.end(); ++cit) {
905 if (is_exactly_a<add>(cit->rest) && cit->coeff.info(info_flags::posint))
908 } else if (is_exactly_a<power>(e)) {
909 if (is_exactly_a<add>(e.op(0)) && e.op(1).info(info_flags::posint))
915 ex mul::expand(unsigned options) const
917 // First, expand the children
918 std::auto_ptr<epvector> expanded_seqp = expandchildren(options);
919 const epvector & expanded_seq = (expanded_seqp.get() ? *expanded_seqp : seq);
921 // Now, look for all the factors that are sums and multiply each one out
922 // with the next one that is found while collecting the factors which are
924 ex last_expanded = _ex1;
927 non_adds.reserve(expanded_seq.size());
929 for (epvector::const_iterator cit = expanded_seq.begin(); cit != expanded_seq.end(); ++cit) {
930 if (is_exactly_a<add>(cit->rest) &&
931 (cit->coeff.is_equal(_ex1))) {
932 if (is_exactly_a<add>(last_expanded)) {
934 // Expand a product of two sums, aggressive version.
935 // Caring for the overall coefficients in separate loops can
936 // sometimes give a performance gain of up to 15%!
938 const int sizedifference = ex_to<add>(last_expanded).seq.size()-ex_to<add>(cit->rest).seq.size();
939 // add2 is for the inner loop and should be the bigger of the two sums
940 // in the presence of asymptotically good sorting:
941 const add& add1 = (sizedifference<0 ? ex_to<add>(last_expanded) : ex_to<add>(cit->rest));
942 const add& add2 = (sizedifference<0 ? ex_to<add>(cit->rest) : ex_to<add>(last_expanded));
943 const epvector::const_iterator add1begin = add1.seq.begin();
944 const epvector::const_iterator add1end = add1.seq.end();
945 const epvector::const_iterator add2begin = add2.seq.begin();
946 const epvector::const_iterator add2end = add2.seq.end();
948 distrseq.reserve(add1.seq.size()+add2.seq.size());
950 // Multiply add2 with the overall coefficient of add1 and append it to distrseq:
951 if (!add1.overall_coeff.is_zero()) {
952 if (add1.overall_coeff.is_equal(_ex1))
953 distrseq.insert(distrseq.end(),add2begin,add2end);
955 for (epvector::const_iterator i=add2begin; i!=add2end; ++i)
956 distrseq.push_back(expair(i->rest, ex_to<numeric>(i->coeff).mul_dyn(ex_to<numeric>(add1.overall_coeff))));
959 // Multiply add1 with the overall coefficient of add2 and append it to distrseq:
960 if (!add2.overall_coeff.is_zero()) {
961 if (add2.overall_coeff.is_equal(_ex1))
962 distrseq.insert(distrseq.end(),add1begin,add1end);
964 for (epvector::const_iterator i=add1begin; i!=add1end; ++i)
965 distrseq.push_back(expair(i->rest, ex_to<numeric>(i->coeff).mul_dyn(ex_to<numeric>(add2.overall_coeff))));
968 // Compute the new overall coefficient and put it together:
969 ex tmp_accu = (new add(distrseq, add1.overall_coeff*add2.overall_coeff))->setflag(status_flags::dynallocated);
971 exvector add1_dummy_indices, add2_dummy_indices, add_indices;
973 for (epvector::const_iterator i=add1begin; i!=add1end; ++i) {
974 add_indices = get_all_dummy_indices(i->rest);
975 add1_dummy_indices.insert(add1_dummy_indices.end(), add_indices.begin(), add_indices.end());
977 for (epvector::const_iterator i=add2begin; i!=add2end; ++i) {
978 add_indices = get_all_dummy_indices(i->rest);
979 add2_dummy_indices.insert(add2_dummy_indices.end(), add_indices.begin(), add_indices.end());
982 sort(add1_dummy_indices.begin(), add1_dummy_indices.end(), ex_is_less());
983 sort(add2_dummy_indices.begin(), add2_dummy_indices.end(), ex_is_less());
984 lst dummy_subs = rename_dummy_indices_uniquely(add1_dummy_indices, add2_dummy_indices);
986 // Multiply explicitly all non-numeric terms of add1 and add2:
987 for (epvector::const_iterator i2=add2begin; i2!=add2end; ++i2) {
988 // We really have to combine terms here in order to compactify
989 // the result. Otherwise it would become waayy tooo bigg.
992 ex i2_new = (dummy_subs.op(0).nops()>0?
993 i2->rest.subs((lst)dummy_subs.op(0), (lst)dummy_subs.op(1), subs_options::no_pattern) : i2->rest);
994 for (epvector::const_iterator i1=add1begin; i1!=add1end; ++i1) {
995 // Don't push_back expairs which might have a rest that evaluates to a numeric,
996 // since that would violate an invariant of expairseq:
997 const ex rest = (new mul(i1->rest, i2_new))->setflag(status_flags::dynallocated);
998 if (is_exactly_a<numeric>(rest)) {
999 oc += ex_to<numeric>(rest).mul(ex_to<numeric>(i1->coeff).mul(ex_to<numeric>(i2->coeff)));
1001 distrseq.push_back(expair(rest, ex_to<numeric>(i1->coeff).mul_dyn(ex_to<numeric>(i2->coeff))));
1004 tmp_accu += (new add(distrseq, oc))->setflag(status_flags::dynallocated);
1006 last_expanded = tmp_accu;
1009 if (!last_expanded.is_equal(_ex1))
1010 non_adds.push_back(split_ex_to_pair(last_expanded));
1011 last_expanded = cit->rest;
1015 non_adds.push_back(*cit);
1019 // Now the only remaining thing to do is to multiply the factors which
1020 // were not sums into the "last_expanded" sum
1021 if (is_exactly_a<add>(last_expanded)) {
1022 size_t n = last_expanded.nops();
1024 distrseq.reserve(n);
1025 exvector va = get_all_dummy_indices(mul(non_adds));
1026 sort(va.begin(), va.end(), ex_is_less());
1028 for (size_t i=0; i<n; ++i) {
1029 epvector factors = non_adds;
1030 factors.push_back(split_ex_to_pair(rename_dummy_indices_uniquely(va, last_expanded.op(i))));
1031 ex term = (new mul(factors, overall_coeff))->setflag(status_flags::dynallocated);
1032 if (can_be_further_expanded(term)) {
1033 distrseq.push_back(term.expand());
1036 ex_to<basic>(term).setflag(status_flags::expanded);
1037 distrseq.push_back(term);
1041 return ((new add(distrseq))->
1042 setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0)));
1045 non_adds.push_back(split_ex_to_pair(last_expanded));
1046 ex result = (new mul(non_adds, overall_coeff))->setflag(status_flags::dynallocated);
1047 if (can_be_further_expanded(result)) {
1048 return result.expand();
1051 ex_to<basic>(result).setflag(status_flags::expanded);
1058 // new virtual functions which can be overridden by derived classes
1064 // non-virtual functions in this class
1068 /** Member-wise expand the expairs representing this sequence. This must be
1069 * overridden from expairseq::expandchildren() and done iteratively in order
1070 * to allow for early cancallations and thus safe memory.
1072 * @see mul::expand()
1073 * @return pointer to epvector containing expanded representation or zero
1074 * pointer, if sequence is unchanged. */
1075 std::auto_ptr<epvector> mul::expandchildren(unsigned options) const
1077 const epvector::const_iterator last = seq.end();
1078 epvector::const_iterator cit = seq.begin();
1080 const ex & factor = recombine_pair_to_ex(*cit);
1081 const ex & expanded_factor = factor.expand(options);
1082 if (!are_ex_trivially_equal(factor,expanded_factor)) {
1084 // something changed, copy seq, eval and return it
1085 std::auto_ptr<epvector> s(new epvector);
1086 s->reserve(seq.size());
1088 // copy parts of seq which are known not to have changed
1089 epvector::const_iterator cit2 = seq.begin();
1091 s->push_back(*cit2);
1095 // copy first changed element
1096 s->push_back(split_ex_to_pair(expanded_factor));
1100 while (cit2!=last) {
1101 s->push_back(split_ex_to_pair(recombine_pair_to_ex(*cit2).expand(options)));
1109 return std::auto_ptr<epvector>(0); // nothing has changed
1112 } // namespace GiNaC