3 * Implementation of GiNaC's products of expressions. */
6 * GiNaC Copyright (C) 1999-2008 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
64 mul::mul(const ex & lh, const ex & rh)
67 construct_from_2_ex(lh,rh);
68 GINAC_ASSERT(is_canonical());
71 mul::mul(const exvector & v)
74 construct_from_exvector(v);
75 GINAC_ASSERT(is_canonical());
78 mul::mul(const epvector & v)
81 construct_from_epvector(v);
82 GINAC_ASSERT(is_canonical());
85 mul::mul(const epvector & v, const ex & oc, bool do_index_renaming)
88 construct_from_epvector(v, do_index_renaming);
89 GINAC_ASSERT(is_canonical());
92 mul::mul(std::auto_ptr<epvector> vp, const ex & oc, bool do_index_renaming)
94 GINAC_ASSERT(vp.get()!=0);
96 construct_from_epvector(*vp, do_index_renaming);
97 GINAC_ASSERT(is_canonical());
100 mul::mul(const ex & lh, const ex & mh, const ex & rh)
104 factors.push_back(lh);
105 factors.push_back(mh);
106 factors.push_back(rh);
107 overall_coeff = _ex1;
108 construct_from_exvector(factors);
109 GINAC_ASSERT(is_canonical());
116 DEFAULT_ARCHIVING(mul)
119 // functions overriding virtual functions from base classes
122 void mul::print_overall_coeff(const print_context & c, const char *mul_sym) const
124 const numeric &coeff = ex_to<numeric>(overall_coeff);
125 if (coeff.csgn() == -1)
127 if (!coeff.is_equal(*_num1_p) &&
128 !coeff.is_equal(*_num_1_p)) {
129 if (coeff.is_rational()) {
130 if (coeff.is_negative())
135 if (coeff.csgn() == -1)
136 (-coeff).print(c, precedence());
138 coeff.print(c, precedence());
144 void mul::do_print(const print_context & c, unsigned level) const
146 if (precedence() <= level)
149 print_overall_coeff(c, "*");
151 epvector::const_iterator it = seq.begin(), itend = seq.end();
153 while (it != itend) {
158 recombine_pair_to_ex(*it).print(c, precedence());
162 if (precedence() <= level)
166 void mul::do_print_latex(const print_latex & c, unsigned level) const
168 if (precedence() <= level)
171 print_overall_coeff(c, " ");
173 // Separate factors into those with negative numeric exponent
175 epvector::const_iterator it = seq.begin(), itend = seq.end();
176 exvector neg_powers, others;
177 while (it != itend) {
178 GINAC_ASSERT(is_exactly_a<numeric>(it->coeff));
179 if (ex_to<numeric>(it->coeff).is_negative())
180 neg_powers.push_back(recombine_pair_to_ex(expair(it->rest, -(it->coeff))));
182 others.push_back(recombine_pair_to_ex(*it));
186 if (!neg_powers.empty()) {
188 // Factors with negative exponent are printed as a fraction
190 mul(others).eval().print(c);
192 mul(neg_powers).eval().print(c);
197 // All other factors are printed in the ordinary way
198 exvector::const_iterator vit = others.begin(), vitend = others.end();
199 while (vit != vitend) {
201 vit->print(c, precedence());
206 if (precedence() <= level)
210 void mul::do_print_csrc(const print_csrc & c, unsigned level) const
212 if (precedence() <= level)
215 if (!overall_coeff.is_equal(_ex1)) {
216 if (overall_coeff.is_equal(_ex_1))
219 overall_coeff.print(c, precedence());
224 // Print arguments, separated by "*" or "/"
225 epvector::const_iterator it = seq.begin(), itend = seq.end();
226 while (it != itend) {
228 // If the first argument is a negative integer power, it gets printed as "1.0/<expr>"
229 bool needclosingparenthesis = false;
230 if (it == seq.begin() && it->coeff.info(info_flags::negint)) {
231 if (is_a<print_csrc_cl_N>(c)) {
233 needclosingparenthesis = true;
238 // If the exponent is 1 or -1, it is left out
239 if (it->coeff.is_equal(_ex1) || it->coeff.is_equal(_ex_1))
240 it->rest.print(c, precedence());
241 else if (it->coeff.info(info_flags::negint))
242 // Outer parens around ex needed for broken GCC parser:
243 (ex(power(it->rest, -ex_to<numeric>(it->coeff)))).print(c, level);
245 // Outer parens around ex needed for broken GCC parser:
246 (ex(power(it->rest, ex_to<numeric>(it->coeff)))).print(c, level);
248 if (needclosingparenthesis)
251 // Separator is "/" for negative integer powers, "*" otherwise
254 if (it->coeff.info(info_flags::negint))
261 if (precedence() <= level)
265 void mul::do_print_python_repr(const print_python_repr & c, unsigned level) const
267 c.s << class_name() << '(';
269 for (size_t i=1; i<nops(); ++i) {
276 bool mul::info(unsigned inf) const
279 case info_flags::polynomial:
280 case info_flags::integer_polynomial:
281 case info_flags::cinteger_polynomial:
282 case info_flags::rational_polynomial:
283 case info_flags::crational_polynomial:
284 case info_flags::rational_function: {
285 epvector::const_iterator i = seq.begin(), end = seq.end();
287 if (!(recombine_pair_to_ex(*i).info(inf)))
291 return overall_coeff.info(inf);
293 case info_flags::algebraic: {
294 epvector::const_iterator i = seq.begin(), end = seq.end();
296 if ((recombine_pair_to_ex(*i).info(inf)))
303 return inherited::info(inf);
306 int mul::degree(const ex & s) const
308 // Sum up degrees of factors
310 epvector::const_iterator i = seq.begin(), end = seq.end();
312 if (ex_to<numeric>(i->coeff).is_integer())
313 deg_sum += recombine_pair_to_ex(*i).degree(s);
316 throw std::runtime_error("mul::degree() undefined degree because of non-integer exponent");
323 int mul::ldegree(const ex & s) const
325 // Sum up degrees of factors
327 epvector::const_iterator i = seq.begin(), end = seq.end();
329 if (ex_to<numeric>(i->coeff).is_integer())
330 deg_sum += recombine_pair_to_ex(*i).ldegree(s);
333 throw std::runtime_error("mul::ldegree() undefined degree because of non-integer exponent");
340 ex mul::coeff(const ex & s, int n) const
343 coeffseq.reserve(seq.size()+1);
346 // product of individual coeffs
347 // if a non-zero power of s is found, the resulting product will be 0
348 epvector::const_iterator i = seq.begin(), end = seq.end();
350 coeffseq.push_back(recombine_pair_to_ex(*i).coeff(s,n));
353 coeffseq.push_back(overall_coeff);
354 return (new mul(coeffseq))->setflag(status_flags::dynallocated);
357 epvector::const_iterator i = seq.begin(), end = seq.end();
358 bool coeff_found = false;
360 ex t = recombine_pair_to_ex(*i);
361 ex c = t.coeff(s, n);
363 coeffseq.push_back(c);
366 coeffseq.push_back(t);
371 coeffseq.push_back(overall_coeff);
372 return (new mul(coeffseq))->setflag(status_flags::dynallocated);
378 /** Perform automatic term rewriting rules in this class. In the following
379 * x, x1, x2,... stand for a symbolic variables of type ex and c, c1, c2...
380 * stand for such expressions that contain a plain number.
382 * - *(+(x1,x2,...);c) -> *(+(*(x1,c),*(x2,c),...))
386 * @param level cut-off in recursive evaluation */
387 ex mul::eval(int level) const
389 std::auto_ptr<epvector> evaled_seqp = evalchildren(level);
390 if (evaled_seqp.get()) {
391 // do more evaluation later
392 return (new mul(evaled_seqp, overall_coeff))->
393 setflag(status_flags::dynallocated);
396 #ifdef DO_GINAC_ASSERT
397 epvector::const_iterator i = seq.begin(), end = seq.end();
399 GINAC_ASSERT((!is_exactly_a<mul>(i->rest)) ||
400 (!(ex_to<numeric>(i->coeff).is_integer())));
401 GINAC_ASSERT(!(i->is_canonical_numeric()));
402 if (is_exactly_a<numeric>(recombine_pair_to_ex(*i)))
403 print(print_tree(std::cerr));
404 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*i)));
406 expair p = split_ex_to_pair(recombine_pair_to_ex(*i));
407 GINAC_ASSERT(p.rest.is_equal(i->rest));
408 GINAC_ASSERT(p.coeff.is_equal(i->coeff));
412 #endif // def DO_GINAC_ASSERT
414 if (flags & status_flags::evaluated) {
415 GINAC_ASSERT(seq.size()>0);
416 GINAC_ASSERT(seq.size()>1 || !overall_coeff.is_equal(_ex1));
420 size_t seq_size = seq.size();
421 if (overall_coeff.is_zero()) {
424 } else if (seq_size==0) {
426 return overall_coeff;
427 } else if (seq_size==1 && overall_coeff.is_equal(_ex1)) {
429 return recombine_pair_to_ex(*(seq.begin()));
430 } else if ((seq_size==1) &&
431 is_exactly_a<add>((*seq.begin()).rest) &&
432 ex_to<numeric>((*seq.begin()).coeff).is_equal(*_num1_p)) {
433 // *(+(x,y,...);c) -> +(*(x,c),*(y,c),...) (c numeric(), no powers of +())
434 const add & addref = ex_to<add>((*seq.begin()).rest);
435 std::auto_ptr<epvector> distrseq(new epvector);
436 distrseq->reserve(addref.seq.size());
437 epvector::const_iterator i = addref.seq.begin(), end = addref.seq.end();
439 distrseq->push_back(addref.combine_pair_with_coeff_to_pair(*i, overall_coeff));
442 return (new add(distrseq,
443 ex_to<numeric>(addref.overall_coeff).
444 mul_dyn(ex_to<numeric>(overall_coeff)))
445 )->setflag(status_flags::dynallocated | status_flags::evaluated);
446 } else if ((seq_size >= 2) && (! (flags & status_flags::expanded))) {
447 // Strip the content and the unit part from each term. Thus
448 // things like (-x+a)*(3*x-3*a) automagically turn into - 3*(x-a)2
450 epvector::const_iterator last = seq.end();
451 epvector::const_iterator i = seq.begin();
452 epvector::const_iterator j = seq.begin();
453 std::auto_ptr<epvector> s(new epvector);
454 numeric oc = *_num1_p;
455 bool something_changed = false;
457 if (likely(! (is_a<add>(i->rest) && i->coeff.is_equal(_ex1)))) {
458 // power::eval has such a rule, no need to handle powers here
463 // XXX: What is the best way to check if the polynomial is a primitive?
464 numeric c = i->rest.integer_content();
465 const numeric lead_coeff =
466 ex_to<numeric>(ex_to<add>(i->rest).seq.begin()->coeff).div(c);
467 const bool canonicalizable = lead_coeff.is_integer();
469 // XXX: The main variable is chosen in a random way, so this code
470 // does NOT transform the term into the canonical form (thus, in some
471 // very unlucky event it can even loop forever). Hopefully the main
472 // variable will be the same for all terms in *this
473 const bool unit_normal = lead_coeff.is_pos_integer();
474 if (likely((c == *_num1_p) && ((! canonicalizable) || unit_normal))) {
479 if (! something_changed) {
480 s->reserve(seq_size);
481 something_changed = true;
484 while ((j!=i) && (j!=last)) {
490 c = c.mul(*_num_1_p);
494 // divide add by the number in place to save at least 2 .eval() calls
495 const add& addref = ex_to<add>(i->rest);
496 add* primitive = new add(addref);
497 primitive->setflag(status_flags::dynallocated);
498 primitive->clearflag(status_flags::hash_calculated);
499 primitive->overall_coeff = ex_to<numeric>(primitive->overall_coeff).div_dyn(c);
500 for (epvector::iterator ai = primitive->seq.begin();
501 ai != primitive->seq.end(); ++ai)
502 ai->coeff = ex_to<numeric>(ai->coeff).div_dyn(c);
504 s->push_back(expair(*primitive, _ex1));
509 if (something_changed) {
514 return (new mul(s, ex_to<numeric>(overall_coeff).mul_dyn(oc))
515 )->setflag(status_flags::dynallocated);
522 ex mul::evalf(int level) const
525 return mul(seq,overall_coeff);
527 if (level==-max_recursion_level)
528 throw(std::runtime_error("max recursion level reached"));
530 std::auto_ptr<epvector> s(new epvector);
531 s->reserve(seq.size());
534 epvector::const_iterator i = seq.begin(), end = seq.end();
536 s->push_back(combine_ex_with_coeff_to_pair(i->rest.evalf(level),
540 return mul(s, overall_coeff.evalf(level));
543 void mul::find_real_imag(ex & rp, ex & ip) const
545 rp = overall_coeff.real_part();
546 ip = overall_coeff.imag_part();
547 for (epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i) {
548 ex factor = recombine_pair_to_ex(*i);
549 ex new_rp = factor.real_part();
550 ex new_ip = factor.imag_part();
551 if(new_ip.is_zero()) {
555 ex temp = rp*new_rp - ip*new_ip;
556 ip = ip*new_rp + rp*new_ip;
564 ex mul::real_part() const
567 find_real_imag(rp, ip);
571 ex mul::imag_part() const
574 find_real_imag(rp, ip);
578 ex mul::evalm() const
581 if (seq.size() == 1 && seq[0].coeff.is_equal(_ex1)
582 && is_a<matrix>(seq[0].rest))
583 return ex_to<matrix>(seq[0].rest).mul(ex_to<numeric>(overall_coeff));
585 // Evaluate children first, look whether there are any matrices at all
586 // (there can be either no matrices or one matrix; if there were more
587 // than one matrix, it would be a non-commutative product)
588 std::auto_ptr<epvector> s(new epvector);
589 s->reserve(seq.size());
591 bool have_matrix = false;
592 epvector::iterator the_matrix;
594 epvector::const_iterator i = seq.begin(), end = seq.end();
596 const ex &m = recombine_pair_to_ex(*i).evalm();
597 s->push_back(split_ex_to_pair(m));
598 if (is_a<matrix>(m)) {
600 the_matrix = s->end() - 1;
607 // The product contained a matrix. We will multiply all other factors
609 matrix m = ex_to<matrix>(the_matrix->rest);
610 s->erase(the_matrix);
611 ex scalar = (new mul(s, overall_coeff))->setflag(status_flags::dynallocated);
612 return m.mul_scalar(scalar);
615 return (new mul(s, overall_coeff))->setflag(status_flags::dynallocated);
618 ex mul::eval_ncmul(const exvector & v) const
621 return inherited::eval_ncmul(v);
623 // Find first noncommutative element and call its eval_ncmul()
624 epvector::const_iterator i = seq.begin(), end = seq.end();
626 if (i->rest.return_type() == return_types::noncommutative)
627 return i->rest.eval_ncmul(v);
630 return inherited::eval_ncmul(v);
633 bool tryfactsubs(const ex & origfactor, const ex & patternfactor, int & nummatches, exmap& repls)
639 if (is_exactly_a<power>(origfactor) && origfactor.op(1).info(info_flags::integer)) {
640 origbase = origfactor.op(0);
641 int expon = ex_to<numeric>(origfactor.op(1)).to_int();
642 origexponent = expon > 0 ? expon : -expon;
643 origexpsign = expon > 0 ? 1 : -1;
645 origbase = origfactor;
654 if (is_exactly_a<power>(patternfactor) && patternfactor.op(1).info(info_flags::integer)) {
655 patternbase = patternfactor.op(0);
656 int expon = ex_to<numeric>(patternfactor.op(1)).to_int();
657 patternexponent = expon > 0 ? expon : -expon;
658 patternexpsign = expon > 0 ? 1 : -1;
660 patternbase = patternfactor;
665 exmap saverepls = repls;
666 if (origexponent < patternexponent || origexpsign != patternexpsign || !origbase.match(patternbase,saverepls))
670 int newnummatches = origexponent / patternexponent;
671 if (newnummatches < nummatches)
672 nummatches = newnummatches;
676 /** Checks wheter e matches to the pattern pat and the (possibly to be updated)
677 * list of replacements repls. This matching is in the sense of algebraic
678 * substitutions. Matching starts with pat.op(factor) of the pattern because
679 * the factors before this one have already been matched. The (possibly
680 * updated) number of matches is in nummatches. subsed[i] is true for factors
681 * that already have been replaced by previous substitutions and matched[i]
682 * is true for factors that have been matched by the current match.
684 bool algebraic_match_mul_with_mul(const mul &e, const ex &pat, exmap& repls,
685 int factor, int &nummatches, const std::vector<bool> &subsed,
686 std::vector<bool> &matched)
688 if (factor == pat.nops())
691 for (size_t i=0; i<e.nops(); ++i) {
692 if(subsed[i] || matched[i])
694 exmap newrepls = repls;
695 int newnummatches = nummatches;
696 if (tryfactsubs(e.op(i), pat.op(factor), newnummatches, newrepls)) {
698 if (algebraic_match_mul_with_mul(e, pat, newrepls, factor+1,
699 newnummatches, subsed, matched)) {
701 nummatches = newnummatches;
712 bool mul::has(const ex & pattern, unsigned options) const
714 if(!(options&has_options::algebraic))
715 return basic::has(pattern,options);
716 if(is_a<mul>(pattern)) {
718 int nummatches = std::numeric_limits<int>::max();
719 std::vector<bool> subsed(seq.size(), false);
720 std::vector<bool> matched(seq.size(), false);
721 if(algebraic_match_mul_with_mul(*this, pattern, repls, 0, nummatches,
725 return basic::has(pattern, options);
728 ex mul::algebraic_subs_mul(const exmap & m, unsigned options) const
730 std::vector<bool> subsed(seq.size(), false);
731 exvector subsresult(seq.size());
735 for (exmap::const_iterator it = m.begin(); it != m.end(); ++it) {
737 if (is_exactly_a<mul>(it->first)) {
739 int nummatches = std::numeric_limits<int>::max();
740 std::vector<bool> currsubsed(seq.size(), false);
743 if(!algebraic_match_mul_with_mul(*this, it->first, repls, 0, nummatches, subsed, currsubsed))
746 for (size_t j=0; j<subsed.size(); j++)
750 = it->first.subs(repls, subs_options::no_pattern);
751 divide_by *= power(subsed_pattern, nummatches);
753 = it->second.subs(repls, subs_options::no_pattern);
754 multiply_by *= power(subsed_result, nummatches);
759 for (size_t j=0; j<this->nops(); j++) {
760 int nummatches = std::numeric_limits<int>::max();
762 if (!subsed[j] && tryfactsubs(op(j), it->first, nummatches, repls)){
765 = it->first.subs(repls, subs_options::no_pattern);
766 divide_by *= power(subsed_pattern, nummatches);
768 = it->second.subs(repls, subs_options::no_pattern);
769 multiply_by *= power(subsed_result, nummatches);
775 bool subsfound = false;
776 for (size_t i=0; i<subsed.size(); i++) {
783 return subs_one_level(m, options | subs_options::algebraic);
785 return ((*this)/divide_by)*multiply_by;
790 /** Implementation of ex::diff() for a product. It applies the product rule.
792 ex mul::derivative(const symbol & s) const
794 size_t num = seq.size();
798 // D(a*b*c) = D(a)*b*c + a*D(b)*c + a*b*D(c)
799 epvector mulseq = seq;
800 epvector::const_iterator i = seq.begin(), end = seq.end();
801 epvector::iterator i2 = mulseq.begin();
803 expair ep = split_ex_to_pair(power(i->rest, i->coeff - _ex1) *
806 addseq.push_back((new mul(mulseq, overall_coeff * i->coeff))->setflag(status_flags::dynallocated));
810 return (new add(addseq))->setflag(status_flags::dynallocated);
813 int mul::compare_same_type(const basic & other) const
815 return inherited::compare_same_type(other);
818 unsigned mul::return_type() const
821 // mul without factors: should not happen, but commutates
822 return return_types::commutative;
825 bool all_commutative = true;
826 epvector::const_iterator noncommutative_element; // point to first found nc element
828 epvector::const_iterator i = seq.begin(), end = seq.end();
830 unsigned rt = i->rest.return_type();
831 if (rt == return_types::noncommutative_composite)
832 return rt; // one ncc -> mul also ncc
833 if ((rt == return_types::noncommutative) && (all_commutative)) {
834 // first nc element found, remember position
835 noncommutative_element = i;
836 all_commutative = false;
838 if ((rt == return_types::noncommutative) && (!all_commutative)) {
839 // another nc element found, compare type_infos
840 if (noncommutative_element->rest.return_type_tinfo() != i->rest.return_type_tinfo()) {
841 // different types -> mul is ncc
842 return return_types::noncommutative_composite;
847 // all factors checked
848 return all_commutative ? return_types::commutative : return_types::noncommutative;
851 return_type_t mul::return_type_tinfo() const
854 return make_return_type_t<mul>(); // mul without factors: should not happen
856 // return type_info of first noncommutative element
857 epvector::const_iterator i = seq.begin(), end = seq.end();
859 if (i->rest.return_type() == return_types::noncommutative)
860 return i->rest.return_type_tinfo();
863 // no noncommutative element found, should not happen
864 return make_return_type_t<mul>();
867 ex mul::thisexpairseq(const epvector & v, const ex & oc, bool do_index_renaming) const
869 return (new mul(v, oc, do_index_renaming))->setflag(status_flags::dynallocated);
872 ex mul::thisexpairseq(std::auto_ptr<epvector> vp, const ex & oc, bool do_index_renaming) const
874 return (new mul(vp, oc, do_index_renaming))->setflag(status_flags::dynallocated);
877 expair mul::split_ex_to_pair(const ex & e) const
879 if (is_exactly_a<power>(e)) {
880 const power & powerref = ex_to<power>(e);
881 if (is_exactly_a<numeric>(powerref.exponent))
882 return expair(powerref.basis,powerref.exponent);
884 return expair(e,_ex1);
887 expair mul::combine_ex_with_coeff_to_pair(const ex & e,
890 // to avoid duplication of power simplification rules,
891 // we create a temporary power object
892 // otherwise it would be hard to correctly evaluate
893 // expression like (4^(1/3))^(3/2)
894 if (c.is_equal(_ex1))
895 return split_ex_to_pair(e);
897 return split_ex_to_pair(power(e,c));
900 expair mul::combine_pair_with_coeff_to_pair(const expair & p,
903 // to avoid duplication of power simplification rules,
904 // we create a temporary power object
905 // otherwise it would be hard to correctly evaluate
906 // expression like (4^(1/3))^(3/2)
907 if (c.is_equal(_ex1))
910 return split_ex_to_pair(power(recombine_pair_to_ex(p),c));
913 ex mul::recombine_pair_to_ex(const expair & p) const
915 if (ex_to<numeric>(p.coeff).is_equal(*_num1_p))
918 return (new power(p.rest,p.coeff))->setflag(status_flags::dynallocated);
921 bool mul::expair_needs_further_processing(epp it)
923 if (is_exactly_a<mul>(it->rest) &&
924 ex_to<numeric>(it->coeff).is_integer()) {
925 // combined pair is product with integer power -> expand it
926 *it = split_ex_to_pair(recombine_pair_to_ex(*it));
929 if (is_exactly_a<numeric>(it->rest)) {
930 expair ep = split_ex_to_pair(recombine_pair_to_ex(*it));
931 if (!ep.is_equal(*it)) {
932 // combined pair is a numeric power which can be simplified
936 if (it->coeff.is_equal(_ex1)) {
937 // combined pair has coeff 1 and must be moved to the end
944 ex mul::default_overall_coeff() const
949 void mul::combine_overall_coeff(const ex & c)
951 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
952 GINAC_ASSERT(is_exactly_a<numeric>(c));
953 overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c));
956 void mul::combine_overall_coeff(const ex & c1, const ex & c2)
958 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
959 GINAC_ASSERT(is_exactly_a<numeric>(c1));
960 GINAC_ASSERT(is_exactly_a<numeric>(c2));
961 overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c1).power(ex_to<numeric>(c2)));
964 bool mul::can_make_flat(const expair & p) const
966 GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
967 // this assertion will probably fail somewhere
968 // it would require a more careful make_flat, obeying the power laws
969 // probably should return true only if p.coeff is integer
970 return ex_to<numeric>(p.coeff).is_equal(*_num1_p);
973 bool mul::can_be_further_expanded(const ex & e)
975 if (is_exactly_a<mul>(e)) {
976 for (epvector::const_iterator cit = ex_to<mul>(e).seq.begin(); cit != ex_to<mul>(e).seq.end(); ++cit) {
977 if (is_exactly_a<add>(cit->rest) && cit->coeff.info(info_flags::posint))
980 } else if (is_exactly_a<power>(e)) {
981 if (is_exactly_a<add>(e.op(0)) && e.op(1).info(info_flags::posint))
987 ex mul::expand(unsigned options) const
990 // trivial case: expanding the monomial (~ 30% of all calls)
991 epvector::const_iterator i = seq.begin(), seq_end = seq.end();
992 while ((i != seq.end()) && is_a<symbol>(i->rest) && i->coeff.info(info_flags::integer))
995 setflag(status_flags::expanded);
1000 // do not rename indices if the object has no indices at all
1001 if ((!(options & expand_options::expand_rename_idx)) &&
1002 this->info(info_flags::has_indices))
1003 options |= expand_options::expand_rename_idx;
1005 const bool skip_idx_rename = !(options & expand_options::expand_rename_idx);
1007 // First, expand the children
1008 std::auto_ptr<epvector> expanded_seqp = expandchildren(options);
1009 const epvector & expanded_seq = (expanded_seqp.get() ? *expanded_seqp : seq);
1011 // Now, look for all the factors that are sums and multiply each one out
1012 // with the next one that is found while collecting the factors which are
1014 ex last_expanded = _ex1;
1017 non_adds.reserve(expanded_seq.size());
1019 for (epvector::const_iterator cit = expanded_seq.begin(); cit != expanded_seq.end(); ++cit) {
1020 if (is_exactly_a<add>(cit->rest) &&
1021 (cit->coeff.is_equal(_ex1))) {
1022 if (is_exactly_a<add>(last_expanded)) {
1024 // Expand a product of two sums, aggressive version.
1025 // Caring for the overall coefficients in separate loops can
1026 // sometimes give a performance gain of up to 15%!
1028 const int sizedifference = ex_to<add>(last_expanded).seq.size()-ex_to<add>(cit->rest).seq.size();
1029 // add2 is for the inner loop and should be the bigger of the two sums
1030 // in the presence of asymptotically good sorting:
1031 const add& add1 = (sizedifference<0 ? ex_to<add>(last_expanded) : ex_to<add>(cit->rest));
1032 const add& add2 = (sizedifference<0 ? ex_to<add>(cit->rest) : ex_to<add>(last_expanded));
1033 const epvector::const_iterator add1begin = add1.seq.begin();
1034 const epvector::const_iterator add1end = add1.seq.end();
1035 const epvector::const_iterator add2begin = add2.seq.begin();
1036 const epvector::const_iterator add2end = add2.seq.end();
1038 distrseq.reserve(add1.seq.size()+add2.seq.size());
1040 // Multiply add2 with the overall coefficient of add1 and append it to distrseq:
1041 if (!add1.overall_coeff.is_zero()) {
1042 if (add1.overall_coeff.is_equal(_ex1))
1043 distrseq.insert(distrseq.end(),add2begin,add2end);
1045 for (epvector::const_iterator i=add2begin; i!=add2end; ++i)
1046 distrseq.push_back(expair(i->rest, ex_to<numeric>(i->coeff).mul_dyn(ex_to<numeric>(add1.overall_coeff))));
1049 // Multiply add1 with the overall coefficient of add2 and append it to distrseq:
1050 if (!add2.overall_coeff.is_zero()) {
1051 if (add2.overall_coeff.is_equal(_ex1))
1052 distrseq.insert(distrseq.end(),add1begin,add1end);
1054 for (epvector::const_iterator i=add1begin; i!=add1end; ++i)
1055 distrseq.push_back(expair(i->rest, ex_to<numeric>(i->coeff).mul_dyn(ex_to<numeric>(add2.overall_coeff))));
1058 // Compute the new overall coefficient and put it together:
1059 ex tmp_accu = (new add(distrseq, add1.overall_coeff*add2.overall_coeff))->setflag(status_flags::dynallocated);
1061 exvector add1_dummy_indices, add2_dummy_indices, add_indices;
1064 if (!skip_idx_rename) {
1065 for (epvector::const_iterator i=add1begin; i!=add1end; ++i) {
1066 add_indices = get_all_dummy_indices_safely(i->rest);
1067 add1_dummy_indices.insert(add1_dummy_indices.end(), add_indices.begin(), add_indices.end());
1069 for (epvector::const_iterator i=add2begin; i!=add2end; ++i) {
1070 add_indices = get_all_dummy_indices_safely(i->rest);
1071 add2_dummy_indices.insert(add2_dummy_indices.end(), add_indices.begin(), add_indices.end());
1074 sort(add1_dummy_indices.begin(), add1_dummy_indices.end(), ex_is_less());
1075 sort(add2_dummy_indices.begin(), add2_dummy_indices.end(), ex_is_less());
1076 dummy_subs = rename_dummy_indices_uniquely(add1_dummy_indices, add2_dummy_indices);
1079 // Multiply explicitly all non-numeric terms of add1 and add2:
1080 for (epvector::const_iterator i2=add2begin; i2!=add2end; ++i2) {
1081 // We really have to combine terms here in order to compactify
1082 // the result. Otherwise it would become waayy tooo bigg.
1083 numeric oc(*_num0_p);
1085 distrseq2.reserve(add1.seq.size());
1086 const ex i2_new = (skip_idx_rename || (dummy_subs.op(0).nops() == 0) ?
1088 i2->rest.subs(ex_to<lst>(dummy_subs.op(0)),
1089 ex_to<lst>(dummy_subs.op(1)), subs_options::no_pattern));
1090 for (epvector::const_iterator i1=add1begin; i1!=add1end; ++i1) {
1091 // Don't push_back expairs which might have a rest that evaluates to a numeric,
1092 // since that would violate an invariant of expairseq:
1093 const ex rest = (new mul(i1->rest, i2_new))->setflag(status_flags::dynallocated);
1094 if (is_exactly_a<numeric>(rest)) {
1095 oc += ex_to<numeric>(rest).mul(ex_to<numeric>(i1->coeff).mul(ex_to<numeric>(i2->coeff)));
1097 distrseq2.push_back(expair(rest, ex_to<numeric>(i1->coeff).mul_dyn(ex_to<numeric>(i2->coeff))));
1100 tmp_accu += (new add(distrseq2, oc))->setflag(status_flags::dynallocated);
1102 last_expanded = tmp_accu;
1104 if (!last_expanded.is_equal(_ex1))
1105 non_adds.push_back(split_ex_to_pair(last_expanded));
1106 last_expanded = cit->rest;
1110 non_adds.push_back(*cit);
1114 // Now the only remaining thing to do is to multiply the factors which
1115 // were not sums into the "last_expanded" sum
1116 if (is_exactly_a<add>(last_expanded)) {
1117 size_t n = last_expanded.nops();
1119 distrseq.reserve(n);
1121 if (! skip_idx_rename) {
1122 va = get_all_dummy_indices_safely(mul(non_adds));
1123 sort(va.begin(), va.end(), ex_is_less());
1126 for (size_t i=0; i<n; ++i) {
1127 epvector factors = non_adds;
1128 if (skip_idx_rename)
1129 factors.push_back(split_ex_to_pair(last_expanded.op(i)));
1131 factors.push_back(split_ex_to_pair(rename_dummy_indices_uniquely(va, last_expanded.op(i))));
1132 ex term = (new mul(factors, overall_coeff))->setflag(status_flags::dynallocated);
1133 if (can_be_further_expanded(term)) {
1134 distrseq.push_back(term.expand());
1137 ex_to<basic>(term).setflag(status_flags::expanded);
1138 distrseq.push_back(term);
1142 return ((new add(distrseq))->
1143 setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0)));
1146 non_adds.push_back(split_ex_to_pair(last_expanded));
1147 ex result = (new mul(non_adds, overall_coeff))->setflag(status_flags::dynallocated);
1148 if (can_be_further_expanded(result)) {
1149 return result.expand();
1152 ex_to<basic>(result).setflag(status_flags::expanded);
1159 // new virtual functions which can be overridden by derived classes
1165 // non-virtual functions in this class
1169 /** Member-wise expand the expairs representing this sequence. This must be
1170 * overridden from expairseq::expandchildren() and done iteratively in order
1171 * to allow for early cancallations and thus safe memory.
1173 * @see mul::expand()
1174 * @return pointer to epvector containing expanded representation or zero
1175 * pointer, if sequence is unchanged. */
1176 std::auto_ptr<epvector> mul::expandchildren(unsigned options) const
1178 const epvector::const_iterator last = seq.end();
1179 epvector::const_iterator cit = seq.begin();
1181 const ex & factor = recombine_pair_to_ex(*cit);
1182 const ex & expanded_factor = factor.expand(options);
1183 if (!are_ex_trivially_equal(factor,expanded_factor)) {
1185 // something changed, copy seq, eval and return it
1186 std::auto_ptr<epvector> s(new epvector);
1187 s->reserve(seq.size());
1189 // copy parts of seq which are known not to have changed
1190 epvector::const_iterator cit2 = seq.begin();
1192 s->push_back(*cit2);
1196 // copy first changed element
1197 s->push_back(split_ex_to_pair(expanded_factor));
1201 while (cit2!=last) {
1202 s->push_back(split_ex_to_pair(recombine_pair_to_ex(*cit2).expand(options)));
1210 return std::auto_ptr<epvector>(0); // nothing has changed
1213 } // namespace GiNaC