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"
42 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(mul, expairseq,
43 print_func<print_context>(&mul::do_print).
44 print_func<print_latex>(&mul::do_print_latex).
45 print_func<print_csrc>(&mul::do_print_csrc).
46 print_func<print_tree>(&mul::do_print_tree).
47 print_func<print_python_repr>(&mul::do_print_python_repr))
51 // default constructor
56 tinfo_key = TINFO_mul;
65 mul::mul(const ex & lh, const ex & rh)
67 tinfo_key = TINFO_mul;
69 construct_from_2_ex(lh,rh);
70 GINAC_ASSERT(is_canonical());
73 mul::mul(const exvector & v)
75 tinfo_key = TINFO_mul;
77 construct_from_exvector(v);
78 GINAC_ASSERT(is_canonical());
81 mul::mul(const epvector & v)
83 tinfo_key = TINFO_mul;
85 construct_from_epvector(v);
86 GINAC_ASSERT(is_canonical());
89 mul::mul(const epvector & v, const ex & oc)
91 tinfo_key = TINFO_mul;
93 construct_from_epvector(v);
94 GINAC_ASSERT(is_canonical());
97 mul::mul(std::auto_ptr<epvector> vp, const ex & oc)
99 tinfo_key = TINFO_mul;
100 GINAC_ASSERT(vp.get()!=0);
102 construct_from_epvector(*vp);
103 GINAC_ASSERT(is_canonical());
106 mul::mul(const ex & lh, const ex & mh, const ex & rh)
108 tinfo_key = TINFO_mul;
111 factors.push_back(lh);
112 factors.push_back(mh);
113 factors.push_back(rh);
114 overall_coeff = _ex1;
115 construct_from_exvector(factors);
116 GINAC_ASSERT(is_canonical());
123 DEFAULT_ARCHIVING(mul)
126 // functions overriding virtual functions from base classes
129 void mul::print_overall_coeff(const print_context & c, const char *mul_sym) const
131 const numeric &coeff = ex_to<numeric>(overall_coeff);
132 if (coeff.csgn() == -1)
134 if (!coeff.is_equal(*_num1_p) &&
135 !coeff.is_equal(*_num_1_p)) {
136 if (coeff.is_rational()) {
137 if (coeff.is_negative())
142 if (coeff.csgn() == -1)
143 (-coeff).print(c, precedence());
145 coeff.print(c, precedence());
151 void mul::do_print(const print_context & c, unsigned level) const
153 if (precedence() <= level)
156 print_overall_coeff(c, "*");
158 epvector::const_iterator it = seq.begin(), itend = seq.end();
160 while (it != itend) {
165 recombine_pair_to_ex(*it).print(c, precedence());
169 if (precedence() <= level)
173 void mul::do_print_latex(const print_latex & c, unsigned level) const
175 if (precedence() <= level)
178 print_overall_coeff(c, " ");
180 // Separate factors into those with negative numeric exponent
182 epvector::const_iterator it = seq.begin(), itend = seq.end();
183 exvector neg_powers, others;
184 while (it != itend) {
185 GINAC_ASSERT(is_exactly_a<numeric>(it->coeff));
186 if (ex_to<numeric>(it->coeff).is_negative())
187 neg_powers.push_back(recombine_pair_to_ex(expair(it->rest, -(it->coeff))));
189 others.push_back(recombine_pair_to_ex(*it));
193 if (!neg_powers.empty()) {
195 // Factors with negative exponent are printed as a fraction
197 mul(others).eval().print(c);
199 mul(neg_powers).eval().print(c);
204 // All other factors are printed in the ordinary way
205 exvector::const_iterator vit = others.begin(), vitend = others.end();
206 while (vit != vitend) {
208 vit->print(c, precedence());
213 if (precedence() <= level)
217 void mul::do_print_csrc(const print_csrc & c, unsigned level) const
219 if (precedence() <= level)
222 if (!overall_coeff.is_equal(_ex1)) {
223 if (overall_coeff.is_equal(_ex_1))
226 overall_coeff.print(c, precedence());
231 // Print arguments, separated by "*" or "/"
232 epvector::const_iterator it = seq.begin(), itend = seq.end();
233 while (it != itend) {
235 // If the first argument is a negative integer power, it gets printed as "1.0/<expr>"
236 bool needclosingparenthesis = false;
237 if (it == seq.begin() && it->coeff.info(info_flags::negint)) {
238 if (is_a<print_csrc_cl_N>(c)) {
240 needclosingparenthesis = true;
245 // If the exponent is 1 or -1, it is left out
246 if (it->coeff.is_equal(_ex1) || it->coeff.is_equal(_ex_1))
247 it->rest.print(c, precedence());
248 else if (it->coeff.info(info_flags::negint))
249 // Outer parens around ex needed for broken GCC parser:
250 (ex(power(it->rest, -ex_to<numeric>(it->coeff)))).print(c, level);
252 // Outer parens around ex needed for broken GCC parser:
253 (ex(power(it->rest, ex_to<numeric>(it->coeff)))).print(c, level);
255 if (needclosingparenthesis)
258 // Separator is "/" for negative integer powers, "*" otherwise
261 if (it->coeff.info(info_flags::negint))
268 if (precedence() <= level)
272 void mul::do_print_python_repr(const print_python_repr & c, unsigned level) const
274 c.s << class_name() << '(';
276 for (size_t i=1; i<nops(); ++i) {
283 bool mul::info(unsigned inf) const
286 case info_flags::polynomial:
287 case info_flags::integer_polynomial:
288 case info_flags::cinteger_polynomial:
289 case info_flags::rational_polynomial:
290 case info_flags::crational_polynomial:
291 case info_flags::rational_function: {
292 epvector::const_iterator i = seq.begin(), end = seq.end();
294 if (!(recombine_pair_to_ex(*i).info(inf)))
298 return overall_coeff.info(inf);
300 case info_flags::algebraic: {
301 epvector::const_iterator i = seq.begin(), end = seq.end();
303 if ((recombine_pair_to_ex(*i).info(inf)))
310 return inherited::info(inf);
313 int mul::degree(const ex & s) const
315 // Sum up degrees of factors
317 epvector::const_iterator i = seq.begin(), end = seq.end();
319 if (ex_to<numeric>(i->coeff).is_integer())
320 deg_sum += i->rest.degree(s) * ex_to<numeric>(i->coeff).to_int();
326 int mul::ldegree(const ex & s) const
328 // Sum up degrees of factors
330 epvector::const_iterator i = seq.begin(), end = seq.end();
332 if (ex_to<numeric>(i->coeff).is_integer())
333 deg_sum += i->rest.ldegree(s) * ex_to<numeric>(i->coeff).to_int();
339 ex mul::coeff(const ex & s, int n) const
342 coeffseq.reserve(seq.size()+1);
345 // product of individual coeffs
346 // if a non-zero power of s is found, the resulting product will be 0
347 epvector::const_iterator i = seq.begin(), end = seq.end();
349 coeffseq.push_back(recombine_pair_to_ex(*i).coeff(s,n));
352 coeffseq.push_back(overall_coeff);
353 return (new mul(coeffseq))->setflag(status_flags::dynallocated);
356 epvector::const_iterator i = seq.begin(), end = seq.end();
357 bool coeff_found = false;
359 ex t = recombine_pair_to_ex(*i);
360 ex c = t.coeff(s, n);
362 coeffseq.push_back(c);
365 coeffseq.push_back(t);
370 coeffseq.push_back(overall_coeff);
371 return (new mul(coeffseq))->setflag(status_flags::dynallocated);
377 /** Perform automatic term rewriting rules in this class. In the following
378 * x, x1, x2,... stand for a symbolic variables of type ex and c, c1, c2...
379 * stand for such expressions that contain a plain number.
381 * - *(+(x1,x2,...);c) -> *(+(*(x1,c),*(x2,c),...))
385 * @param level cut-off in recursive evaluation */
386 ex mul::eval(int level) const
388 std::auto_ptr<epvector> evaled_seqp = evalchildren(level);
389 if (evaled_seqp.get()) {
390 // do more evaluation later
391 return (new mul(evaled_seqp, overall_coeff))->
392 setflag(status_flags::dynallocated);
395 #ifdef DO_GINAC_ASSERT
396 epvector::const_iterator i = seq.begin(), end = seq.end();
398 GINAC_ASSERT((!is_exactly_a<mul>(i->rest)) ||
399 (!(ex_to<numeric>(i->coeff).is_integer())));
400 GINAC_ASSERT(!(i->is_canonical_numeric()));
401 if (is_exactly_a<numeric>(recombine_pair_to_ex(*i)))
402 print(print_tree(std::cerr));
403 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*i)));
405 expair p = split_ex_to_pair(recombine_pair_to_ex(*i));
406 GINAC_ASSERT(p.rest.is_equal(i->rest));
407 GINAC_ASSERT(p.coeff.is_equal(i->coeff));
411 #endif // def DO_GINAC_ASSERT
413 if (flags & status_flags::evaluated) {
414 GINAC_ASSERT(seq.size()>0);
415 GINAC_ASSERT(seq.size()>1 || !overall_coeff.is_equal(_ex1));
419 size_t seq_size = seq.size();
420 if (overall_coeff.is_zero()) {
423 } else if (seq_size==0) {
425 return overall_coeff;
426 } else if (seq_size==1 && overall_coeff.is_equal(_ex1)) {
428 return recombine_pair_to_ex(*(seq.begin()));
429 } else if ((seq_size==1) &&
430 is_exactly_a<add>((*seq.begin()).rest) &&
431 ex_to<numeric>((*seq.begin()).coeff).is_equal(*_num1_p)) {
432 // *(+(x,y,...);c) -> +(*(x,c),*(y,c),...) (c numeric(), no powers of +())
433 const add & addref = ex_to<add>((*seq.begin()).rest);
434 std::auto_ptr<epvector> distrseq(new epvector);
435 distrseq->reserve(addref.seq.size());
436 epvector::const_iterator i = addref.seq.begin(), end = addref.seq.end();
438 distrseq->push_back(addref.combine_pair_with_coeff_to_pair(*i, overall_coeff));
441 return (new add(distrseq,
442 ex_to<numeric>(addref.overall_coeff).
443 mul_dyn(ex_to<numeric>(overall_coeff))))
444 ->setflag(status_flags::dynallocated | status_flags::evaluated);
445 } else if ((seq_size >= 2) && (! (flags & status_flags::expanded))) {
446 // Strip the content and the unit part from each term. Thus
447 // things like (-x+a)*(3*x-3*a) automagically turn into - 3*(x-a)2
449 epvector::const_iterator last = seq.end();
450 epvector::const_iterator i = seq.begin();
451 epvector::const_iterator j = seq.begin();
452 std::auto_ptr<epvector> s(new epvector);
453 numeric oc = *_num1_p;
454 bool something_changed = false;
456 if (likely(! (is_a<add>(i->rest) && i->coeff.is_equal(_ex1)))) {
457 // power::eval has such a rule, no need to handle powers here
462 // XXX: What is the best way to check if the polynomial is a primitive?
463 numeric c = i->rest.integer_content();
464 const numeric& lead_coeff =
465 ex_to<numeric>(ex_to<add>(i->rest).seq.begin()->coeff).div_dyn(c);
466 const bool canonicalizable = lead_coeff.is_integer();
468 // XXX: The main variable is chosen in a random way, so this code
469 // does NOT transform the term into the canonical form (thus, in some
470 // very unlucky event it can even loop forever). Hopefully the main
471 // variable will be the same for all terms in *this
472 const bool unit_normal = lead_coeff.is_pos_integer();
473 if (likely((c == *_num1_p) && ((! canonicalizable) || unit_normal))) {
478 if (! something_changed) {
479 s->reserve(seq_size);
480 something_changed = true;
483 while ((j!=i) && (j!=last)) {
489 c = c.mul(*_num_1_p);
493 // divide add by the number in place to save at least 2 .eval() calls
494 const add& addref = ex_to<add>(i->rest);
495 add* primitive = new add(addref);
496 primitive->setflag(status_flags::dynallocated);
497 primitive->clearflag(status_flags::hash_calculated);
498 primitive->overall_coeff = ex_to<numeric>(primitive->overall_coeff).div_dyn(c);
499 for (epvector::iterator ai = primitive->seq.begin();
500 ai != primitive->seq.end(); ++ai)
501 ai->coeff = ex_to<numeric>(ai->coeff).div_dyn(c);
503 s->push_back(expair(*primitive, _ex1));
508 if (something_changed) {
513 return (new mul(s, ex_to<numeric>(overall_coeff).mul_dyn(oc))
514 )->setflag(status_flags::dynallocated);
521 ex mul::evalf(int level) const
524 return mul(seq,overall_coeff);
526 if (level==-max_recursion_level)
527 throw(std::runtime_error("max recursion level reached"));
529 std::auto_ptr<epvector> s(new epvector);
530 s->reserve(seq.size());
533 epvector::const_iterator i = seq.begin(), end = seq.end();
535 s->push_back(combine_ex_with_coeff_to_pair(i->rest.evalf(level),
539 return mul(s, overall_coeff.evalf(level));
542 ex mul::evalm() const
545 if (seq.size() == 1 && seq[0].coeff.is_equal(_ex1)
546 && is_a<matrix>(seq[0].rest))
547 return ex_to<matrix>(seq[0].rest).mul(ex_to<numeric>(overall_coeff));
549 // Evaluate children first, look whether there are any matrices at all
550 // (there can be either no matrices or one matrix; if there were more
551 // than one matrix, it would be a non-commutative product)
552 std::auto_ptr<epvector> s(new epvector);
553 s->reserve(seq.size());
555 bool have_matrix = false;
556 epvector::iterator the_matrix;
558 epvector::const_iterator i = seq.begin(), end = seq.end();
560 const ex &m = recombine_pair_to_ex(*i).evalm();
561 s->push_back(split_ex_to_pair(m));
562 if (is_a<matrix>(m)) {
564 the_matrix = s->end() - 1;
571 // The product contained a matrix. We will multiply all other factors
573 matrix m = ex_to<matrix>(the_matrix->rest);
574 s->erase(the_matrix);
575 ex scalar = (new mul(s, overall_coeff))->setflag(status_flags::dynallocated);
576 return m.mul_scalar(scalar);
579 return (new mul(s, overall_coeff))->setflag(status_flags::dynallocated);
582 ex mul::eval_ncmul(const exvector & v) const
585 return inherited::eval_ncmul(v);
587 // Find first noncommutative element and call its eval_ncmul()
588 epvector::const_iterator i = seq.begin(), end = seq.end();
590 if (i->rest.return_type() == return_types::noncommutative)
591 return i->rest.eval_ncmul(v);
594 return inherited::eval_ncmul(v);
597 bool tryfactsubs(const ex & origfactor, const ex & patternfactor, int & nummatches, lst & repls)
603 if (is_exactly_a<power>(origfactor) && origfactor.op(1).info(info_flags::integer)) {
604 origbase = origfactor.op(0);
605 int expon = ex_to<numeric>(origfactor.op(1)).to_int();
606 origexponent = expon > 0 ? expon : -expon;
607 origexpsign = expon > 0 ? 1 : -1;
609 origbase = origfactor;
618 if (is_exactly_a<power>(patternfactor) && patternfactor.op(1).info(info_flags::integer)) {
619 patternbase = patternfactor.op(0);
620 int expon = ex_to<numeric>(patternfactor.op(1)).to_int();
621 patternexponent = expon > 0 ? expon : -expon;
622 patternexpsign = expon > 0 ? 1 : -1;
624 patternbase = patternfactor;
629 lst saverepls = repls;
630 if (origexponent < patternexponent || origexpsign != patternexpsign || !origbase.match(patternbase,saverepls))
634 int newnummatches = origexponent / patternexponent;
635 if (newnummatches < nummatches)
636 nummatches = newnummatches;
640 /** Checks wheter e matches to the pattern pat and the (possibly to be updated
641 * list of replacements repls. This matching is in the sense of algebraic
642 * substitutions. Matching starts with pat.op(factor) of the pattern because
643 * the factors before this one have already been matched. The (possibly
644 * updated) number of matches is in nummatches. subsed[i] is true for factors
645 * that already have been replaced by previous substitutions and matched[i]
646 * is true for factors that have been matched by the current match.
648 bool algebraic_match_mul_with_mul(const mul &e, const ex &pat, lst &repls,
649 int factor, int &nummatches, const std::vector<bool> &subsed,
650 std::vector<bool> &matched)
652 if (factor == pat.nops())
655 for (size_t i=0; i<e.nops(); ++i) {
656 if(subsed[i] || matched[i])
658 lst newrepls = repls;
659 int newnummatches = nummatches;
660 if (tryfactsubs(e.op(i), pat.op(factor), newnummatches, newrepls)) {
662 if (algebraic_match_mul_with_mul(e, pat, newrepls, factor+1,
663 newnummatches, subsed, matched)) {
665 nummatches = newnummatches;
676 ex mul::algebraic_subs_mul(const exmap & m, unsigned options) const
678 std::vector<bool> subsed(seq.size(), false);
679 exvector subsresult(seq.size());
681 for (exmap::const_iterator it = m.begin(); it != m.end(); ++it) {
683 if (is_exactly_a<mul>(it->first)) {
685 int nummatches = std::numeric_limits<int>::max();
686 std::vector<bool> currsubsed(seq.size(), false);
690 if(!algebraic_match_mul_with_mul(*this, it->first, repls, 0, nummatches, subsed, currsubsed))
693 bool foundfirstsubsedfactor = false;
694 for (size_t j=0; j<subsed.size(); j++) {
696 if (foundfirstsubsedfactor)
697 subsresult[j] = op(j);
699 foundfirstsubsedfactor = true;
700 subsresult[j] = op(j) * power(it->second.subs(ex(repls), subs_options::no_pattern) / it->first.subs(ex(repls), subs_options::no_pattern), nummatches);
709 int nummatches = std::numeric_limits<int>::max();
712 for (size_t j=0; j<this->nops(); j++) {
713 if (!subsed[j] && tryfactsubs(op(j), it->first, nummatches, repls)) {
715 subsresult[j] = op(j) * power(it->second.subs(ex(repls), subs_options::no_pattern) / it->first.subs(ex(repls), subs_options::no_pattern), nummatches);
722 bool subsfound = false;
723 for (size_t i=0; i<subsed.size(); i++) {
730 return subs_one_level(m, options | subs_options::algebraic);
732 exvector ev; ev.reserve(nops());
733 for (size_t i=0; i<nops(); i++) {
735 ev.push_back(subsresult[i]);
740 return (new mul(ev))->setflag(status_flags::dynallocated);
745 /** Implementation of ex::diff() for a product. It applies the product rule.
747 ex mul::derivative(const symbol & s) const
749 size_t num = seq.size();
753 // D(a*b*c) = D(a)*b*c + a*D(b)*c + a*b*D(c)
754 epvector mulseq = seq;
755 epvector::const_iterator i = seq.begin(), end = seq.end();
756 epvector::iterator i2 = mulseq.begin();
758 expair ep = split_ex_to_pair(power(i->rest, i->coeff - _ex1) *
761 addseq.push_back((new mul(mulseq, overall_coeff * i->coeff))->setflag(status_flags::dynallocated));
765 return (new add(addseq))->setflag(status_flags::dynallocated);
768 int mul::compare_same_type(const basic & other) const
770 return inherited::compare_same_type(other);
773 unsigned mul::return_type() const
776 // mul without factors: should not happen, but commutates
777 return return_types::commutative;
780 bool all_commutative = true;
781 epvector::const_iterator noncommutative_element; // point to first found nc element
783 epvector::const_iterator i = seq.begin(), end = seq.end();
785 unsigned rt = i->rest.return_type();
786 if (rt == return_types::noncommutative_composite)
787 return rt; // one ncc -> mul also ncc
788 if ((rt == return_types::noncommutative) && (all_commutative)) {
789 // first nc element found, remember position
790 noncommutative_element = i;
791 all_commutative = false;
793 if ((rt == return_types::noncommutative) && (!all_commutative)) {
794 // another nc element found, compare type_infos
795 if (noncommutative_element->rest.return_type_tinfo() != i->rest.return_type_tinfo()) {
796 // diffent types -> mul is ncc
797 return return_types::noncommutative_composite;
802 // all factors checked
803 return all_commutative ? return_types::commutative : return_types::noncommutative;
806 unsigned mul::return_type_tinfo() const
809 return tinfo_key; // mul without factors: should not happen
811 // return type_info of first noncommutative element
812 epvector::const_iterator i = seq.begin(), end = seq.end();
814 if (i->rest.return_type() == return_types::noncommutative)
815 return i->rest.return_type_tinfo();
818 // no noncommutative element found, should not happen
822 ex mul::thisexpairseq(const epvector & v, const ex & oc) const
824 return (new mul(v, oc))->setflag(status_flags::dynallocated);
827 ex mul::thisexpairseq(std::auto_ptr<epvector> vp, const ex & oc) const
829 return (new mul(vp, oc))->setflag(status_flags::dynallocated);
832 expair mul::split_ex_to_pair(const ex & e) const
834 if (is_exactly_a<power>(e)) {
835 const power & powerref = ex_to<power>(e);
836 if (is_exactly_a<numeric>(powerref.exponent))
837 return expair(powerref.basis,powerref.exponent);
839 return expair(e,_ex1);
842 expair mul::combine_ex_with_coeff_to_pair(const ex & e,
845 // to avoid duplication of power simplification rules,
846 // we create a temporary power object
847 // otherwise it would be hard to correctly evaluate
848 // expression like (4^(1/3))^(3/2)
849 if (c.is_equal(_ex1))
850 return split_ex_to_pair(e);
852 return split_ex_to_pair(power(e,c));
855 expair mul::combine_pair_with_coeff_to_pair(const expair & p,
858 // to avoid duplication of power simplification rules,
859 // we create a temporary power object
860 // otherwise it would be hard to correctly evaluate
861 // expression like (4^(1/3))^(3/2)
862 if (c.is_equal(_ex1))
865 return split_ex_to_pair(power(recombine_pair_to_ex(p),c));
868 ex mul::recombine_pair_to_ex(const expair & p) const
870 if (ex_to<numeric>(p.coeff).is_equal(*_num1_p))
873 return (new power(p.rest,p.coeff))->setflag(status_flags::dynallocated);
876 bool mul::expair_needs_further_processing(epp it)
878 if (is_exactly_a<mul>(it->rest) &&
879 ex_to<numeric>(it->coeff).is_integer()) {
880 // combined pair is product with integer power -> expand it
881 *it = split_ex_to_pair(recombine_pair_to_ex(*it));
884 if (is_exactly_a<numeric>(it->rest)) {
885 expair ep = split_ex_to_pair(recombine_pair_to_ex(*it));
886 if (!ep.is_equal(*it)) {
887 // combined pair is a numeric power which can be simplified
891 if (it->coeff.is_equal(_ex1)) {
892 // combined pair has coeff 1 and must be moved to the end
899 ex mul::default_overall_coeff() const
904 void mul::combine_overall_coeff(const ex & c)
906 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
907 GINAC_ASSERT(is_exactly_a<numeric>(c));
908 overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c));
911 void mul::combine_overall_coeff(const ex & c1, const ex & c2)
913 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
914 GINAC_ASSERT(is_exactly_a<numeric>(c1));
915 GINAC_ASSERT(is_exactly_a<numeric>(c2));
916 overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c1).power(ex_to<numeric>(c2)));
919 bool mul::can_make_flat(const expair & p) const
921 GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
922 // this assertion will probably fail somewhere
923 // it would require a more careful make_flat, obeying the power laws
924 // probably should return true only if p.coeff is integer
925 return ex_to<numeric>(p.coeff).is_equal(*_num1_p);
928 bool mul::can_be_further_expanded(const ex & e)
930 if (is_exactly_a<mul>(e)) {
931 for (epvector::const_iterator cit = ex_to<mul>(e).seq.begin(); cit != ex_to<mul>(e).seq.end(); ++cit) {
932 if (is_exactly_a<add>(cit->rest) && cit->coeff.info(info_flags::posint))
935 } else if (is_exactly_a<power>(e)) {
936 if (is_exactly_a<add>(e.op(0)) && e.op(1).info(info_flags::posint))
942 ex mul::expand(unsigned options) const
945 // trivial case: expanding the monomial (~ 30% of all calls)
946 epvector::const_iterator i = seq.begin(), seq_end = seq.end();
947 while ((i != seq.end()) && is_a<symbol>(i->rest) && i->coeff.info(info_flags::integer))
950 setflag(status_flags::expanded);
955 // do not rename indices if the object has no indices at all
956 if ((!(options & expand_options::expand_rename_idx)) &&
957 this->info(info_flags::has_indices))
958 options |= expand_options::expand_rename_idx;
960 const bool skip_idx_rename = !(options & expand_options::expand_rename_idx);
962 // First, expand the children
963 std::auto_ptr<epvector> expanded_seqp = expandchildren(options);
964 const epvector & expanded_seq = (expanded_seqp.get() ? *expanded_seqp : seq);
966 // Now, look for all the factors that are sums and multiply each one out
967 // with the next one that is found while collecting the factors which are
969 ex last_expanded = _ex1;
972 non_adds.reserve(expanded_seq.size());
974 for (epvector::const_iterator cit = expanded_seq.begin(); cit != expanded_seq.end(); ++cit) {
975 if (is_exactly_a<add>(cit->rest) &&
976 (cit->coeff.is_equal(_ex1))) {
977 if (is_exactly_a<add>(last_expanded)) {
979 // Expand a product of two sums, aggressive version.
980 // Caring for the overall coefficients in separate loops can
981 // sometimes give a performance gain of up to 15%!
983 const int sizedifference = ex_to<add>(last_expanded).seq.size()-ex_to<add>(cit->rest).seq.size();
984 // add2 is for the inner loop and should be the bigger of the two sums
985 // in the presence of asymptotically good sorting:
986 const add& add1 = (sizedifference<0 ? ex_to<add>(last_expanded) : ex_to<add>(cit->rest));
987 const add& add2 = (sizedifference<0 ? ex_to<add>(cit->rest) : ex_to<add>(last_expanded));
988 const epvector::const_iterator add1begin = add1.seq.begin();
989 const epvector::const_iterator add1end = add1.seq.end();
990 const epvector::const_iterator add2begin = add2.seq.begin();
991 const epvector::const_iterator add2end = add2.seq.end();
993 distrseq.reserve(add1.seq.size()+add2.seq.size());
995 // Multiply add2 with the overall coefficient of add1 and append it to distrseq:
996 if (!add1.overall_coeff.is_zero()) {
997 if (add1.overall_coeff.is_equal(_ex1))
998 distrseq.insert(distrseq.end(),add2begin,add2end);
1000 for (epvector::const_iterator i=add2begin; i!=add2end; ++i)
1001 distrseq.push_back(expair(i->rest, ex_to<numeric>(i->coeff).mul_dyn(ex_to<numeric>(add1.overall_coeff))));
1004 // Multiply add1 with the overall coefficient of add2 and append it to distrseq:
1005 if (!add2.overall_coeff.is_zero()) {
1006 if (add2.overall_coeff.is_equal(_ex1))
1007 distrseq.insert(distrseq.end(),add1begin,add1end);
1009 for (epvector::const_iterator i=add1begin; i!=add1end; ++i)
1010 distrseq.push_back(expair(i->rest, ex_to<numeric>(i->coeff).mul_dyn(ex_to<numeric>(add2.overall_coeff))));
1013 // Compute the new overall coefficient and put it together:
1014 ex tmp_accu = (new add(distrseq, add1.overall_coeff*add2.overall_coeff))->setflag(status_flags::dynallocated);
1016 // Multiply explicitly all non-numeric terms of add1 and add2:
1017 for (epvector::const_iterator i1=add1begin; i1!=add1end; ++i1) {
1018 // We really have to combine terms here in order to compactify
1019 // the result. Otherwise it would become waayy tooo bigg.
1022 for (epvector::const_iterator i2=add2begin; i2!=add2end; ++i2) {
1023 // Don't push_back expairs which might have a rest that evaluates to a numeric,
1024 // since that would violate an invariant of expairseq:
1025 const ex rest = (new mul(i1->rest, skip_idx_rename ? i2->rest : rename_dummy_indices_uniquely(i1->rest, i2->rest)))->setflag(status_flags::dynallocated);
1026 if (is_exactly_a<numeric>(rest)) {
1027 oc += ex_to<numeric>(rest).mul(ex_to<numeric>(i1->coeff).mul(ex_to<numeric>(i2->coeff)));
1029 distrseq.push_back(expair(rest, ex_to<numeric>(i1->coeff).mul_dyn(ex_to<numeric>(i2->coeff))));
1032 tmp_accu += (new add(distrseq, oc))->setflag(status_flags::dynallocated);
1034 last_expanded = tmp_accu;
1037 if (!last_expanded.is_equal(_ex1))
1038 non_adds.push_back(split_ex_to_pair(last_expanded));
1039 last_expanded = cit->rest;
1043 non_adds.push_back(*cit);
1047 // Now the only remaining thing to do is to multiply the factors which
1048 // were not sums into the "last_expanded" sum
1049 if (is_exactly_a<add>(last_expanded)) {
1050 size_t n = last_expanded.nops();
1052 distrseq.reserve(n);
1054 for (size_t i=0; i<n; ++i) {
1055 epvector factors = non_adds;
1056 if (skip_idx_rename)
1057 factors.push_back(split_ex_to_pair(last_expanded.op(i)));
1059 factors.push_back(split_ex_to_pair(rename_dummy_indices_uniquely(mul(non_adds), last_expanded.op(i))));
1060 ex term = (new mul(factors, overall_coeff))->setflag(status_flags::dynallocated);
1061 if (can_be_further_expanded(term)) {
1062 distrseq.push_back(term.expand());
1065 ex_to<basic>(term).setflag(status_flags::expanded);
1066 distrseq.push_back(term);
1070 return ((new add(distrseq))->
1071 setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0)));
1074 non_adds.push_back(split_ex_to_pair(last_expanded));
1075 ex result = (new mul(non_adds, overall_coeff))->setflag(status_flags::dynallocated);
1076 if (can_be_further_expanded(result)) {
1077 return result.expand();
1080 ex_to<basic>(result).setflag(status_flags::expanded);
1087 // new virtual functions which can be overridden by derived classes
1093 // non-virtual functions in this class
1097 /** Member-wise expand the expairs representing this sequence. This must be
1098 * overridden from expairseq::expandchildren() and done iteratively in order
1099 * to allow for early cancallations and thus safe memory.
1101 * @see mul::expand()
1102 * @return pointer to epvector containing expanded representation or zero
1103 * pointer, if sequence is unchanged. */
1104 std::auto_ptr<epvector> mul::expandchildren(unsigned options) const
1106 const epvector::const_iterator last = seq.end();
1107 epvector::const_iterator cit = seq.begin();
1109 const ex & factor = recombine_pair_to_ex(*cit);
1110 const ex & expanded_factor = factor.expand(options);
1111 if (!are_ex_trivially_equal(factor,expanded_factor)) {
1113 // something changed, copy seq, eval and return it
1114 std::auto_ptr<epvector> s(new epvector);
1115 s->reserve(seq.size());
1117 // copy parts of seq which are known not to have changed
1118 epvector::const_iterator cit2 = seq.begin();
1120 s->push_back(*cit2);
1124 // copy first changed element
1125 s->push_back(split_ex_to_pair(expanded_factor));
1129 while (cit2!=last) {
1130 s->push_back(split_ex_to_pair(recombine_pair_to_ex(*cit2).expand(options)));
1138 return std::auto_ptr<epvector>(0); // nothing has changed
1141 } // namespace GiNaC