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());
117 // functions overriding virtual functions from base classes
120 void mul::print_overall_coeff(const print_context & c, const char *mul_sym) const
122 const numeric &coeff = ex_to<numeric>(overall_coeff);
123 if (coeff.csgn() == -1)
125 if (!coeff.is_equal(*_num1_p) &&
126 !coeff.is_equal(*_num_1_p)) {
127 if (coeff.is_rational()) {
128 if (coeff.is_negative())
133 if (coeff.csgn() == -1)
134 (-coeff).print(c, precedence());
136 coeff.print(c, precedence());
142 void mul::do_print(const print_context & c, unsigned level) const
144 if (precedence() <= level)
147 print_overall_coeff(c, "*");
149 epvector::const_iterator it = seq.begin(), itend = seq.end();
151 while (it != itend) {
156 recombine_pair_to_ex(*it).print(c, precedence());
160 if (precedence() <= level)
164 void mul::do_print_latex(const print_latex & c, unsigned level) const
166 if (precedence() <= level)
169 print_overall_coeff(c, " ");
171 // Separate factors into those with negative numeric exponent
173 epvector::const_iterator it = seq.begin(), itend = seq.end();
174 exvector neg_powers, others;
175 while (it != itend) {
176 GINAC_ASSERT(is_exactly_a<numeric>(it->coeff));
177 if (ex_to<numeric>(it->coeff).is_negative())
178 neg_powers.push_back(recombine_pair_to_ex(expair(it->rest, -(it->coeff))));
180 others.push_back(recombine_pair_to_ex(*it));
184 if (!neg_powers.empty()) {
186 // Factors with negative exponent are printed as a fraction
188 mul(others).eval().print(c);
190 mul(neg_powers).eval().print(c);
195 // All other factors are printed in the ordinary way
196 exvector::const_iterator vit = others.begin(), vitend = others.end();
197 while (vit != vitend) {
199 vit->print(c, precedence());
204 if (precedence() <= level)
208 void mul::do_print_csrc(const print_csrc & c, unsigned level) const
210 if (precedence() <= level)
213 if (!overall_coeff.is_equal(_ex1)) {
214 if (overall_coeff.is_equal(_ex_1))
217 overall_coeff.print(c, precedence());
222 // Print arguments, separated by "*" or "/"
223 epvector::const_iterator it = seq.begin(), itend = seq.end();
224 while (it != itend) {
226 // If the first argument is a negative integer power, it gets printed as "1.0/<expr>"
227 bool needclosingparenthesis = false;
228 if (it == seq.begin() && it->coeff.info(info_flags::negint)) {
229 if (is_a<print_csrc_cl_N>(c)) {
231 needclosingparenthesis = true;
236 // If the exponent is 1 or -1, it is left out
237 if (it->coeff.is_equal(_ex1) || it->coeff.is_equal(_ex_1))
238 it->rest.print(c, precedence());
239 else if (it->coeff.info(info_flags::negint))
240 // Outer parens around ex needed for broken GCC parser:
241 (ex(power(it->rest, -ex_to<numeric>(it->coeff)))).print(c, level);
243 // Outer parens around ex needed for broken GCC parser:
244 (ex(power(it->rest, ex_to<numeric>(it->coeff)))).print(c, level);
246 if (needclosingparenthesis)
249 // Separator is "/" for negative integer powers, "*" otherwise
252 if (it->coeff.info(info_flags::negint))
259 if (precedence() <= level)
263 void mul::do_print_python_repr(const print_python_repr & c, unsigned level) const
265 c.s << class_name() << '(';
267 for (size_t i=1; i<nops(); ++i) {
274 bool mul::info(unsigned inf) const
277 case info_flags::polynomial:
278 case info_flags::integer_polynomial:
279 case info_flags::cinteger_polynomial:
280 case info_flags::rational_polynomial:
281 case info_flags::crational_polynomial:
282 case info_flags::rational_function: {
283 epvector::const_iterator i = seq.begin(), end = seq.end();
285 if (!(recombine_pair_to_ex(*i).info(inf)))
289 return overall_coeff.info(inf);
291 case info_flags::algebraic: {
292 epvector::const_iterator i = seq.begin(), end = seq.end();
294 if ((recombine_pair_to_ex(*i).info(inf)))
301 return inherited::info(inf);
304 int mul::degree(const ex & s) const
306 // Sum up degrees of factors
308 epvector::const_iterator i = seq.begin(), end = seq.end();
310 if (ex_to<numeric>(i->coeff).is_integer())
311 deg_sum += recombine_pair_to_ex(*i).degree(s);
314 throw std::runtime_error("mul::degree() undefined degree because of non-integer exponent");
321 int mul::ldegree(const ex & s) const
323 // Sum up degrees of factors
325 epvector::const_iterator i = seq.begin(), end = seq.end();
327 if (ex_to<numeric>(i->coeff).is_integer())
328 deg_sum += recombine_pair_to_ex(*i).ldegree(s);
331 throw std::runtime_error("mul::ldegree() undefined degree because of non-integer exponent");
338 ex mul::coeff(const ex & s, int n) const
341 coeffseq.reserve(seq.size()+1);
344 // product of individual coeffs
345 // if a non-zero power of s is found, the resulting product will be 0
346 epvector::const_iterator i = seq.begin(), end = seq.end();
348 coeffseq.push_back(recombine_pair_to_ex(*i).coeff(s,n));
351 coeffseq.push_back(overall_coeff);
352 return (new mul(coeffseq))->setflag(status_flags::dynallocated);
355 epvector::const_iterator i = seq.begin(), end = seq.end();
356 bool coeff_found = false;
358 ex t = recombine_pair_to_ex(*i);
359 ex c = t.coeff(s, n);
361 coeffseq.push_back(c);
364 coeffseq.push_back(t);
369 coeffseq.push_back(overall_coeff);
370 return (new mul(coeffseq))->setflag(status_flags::dynallocated);
376 /** Perform automatic term rewriting rules in this class. In the following
377 * x, x1, x2,... stand for a symbolic variables of type ex and c, c1, c2...
378 * stand for such expressions that contain a plain number.
380 * - *(+(x1,x2,...);c) -> *(+(*(x1,c),*(x2,c),...))
384 * @param level cut-off in recursive evaluation */
385 ex mul::eval(int level) const
387 std::auto_ptr<epvector> evaled_seqp = evalchildren(level);
388 if (evaled_seqp.get()) {
389 // do more evaluation later
390 return (new mul(evaled_seqp, overall_coeff))->
391 setflag(status_flags::dynallocated);
394 #ifdef DO_GINAC_ASSERT
395 epvector::const_iterator i = seq.begin(), end = seq.end();
397 GINAC_ASSERT((!is_exactly_a<mul>(i->rest)) ||
398 (!(ex_to<numeric>(i->coeff).is_integer())));
399 GINAC_ASSERT(!(i->is_canonical_numeric()));
400 if (is_exactly_a<numeric>(recombine_pair_to_ex(*i)))
401 print(print_tree(std::cerr));
402 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*i)));
404 expair p = split_ex_to_pair(recombine_pair_to_ex(*i));
405 GINAC_ASSERT(p.rest.is_equal(i->rest));
406 GINAC_ASSERT(p.coeff.is_equal(i->coeff));
410 #endif // def DO_GINAC_ASSERT
412 if (flags & status_flags::evaluated) {
413 GINAC_ASSERT(seq.size()>0);
414 GINAC_ASSERT(seq.size()>1 || !overall_coeff.is_equal(_ex1));
418 size_t seq_size = seq.size();
419 if (overall_coeff.is_zero()) {
422 } else if (seq_size==0) {
424 return overall_coeff;
425 } else if (seq_size==1 && overall_coeff.is_equal(_ex1)) {
427 return recombine_pair_to_ex(*(seq.begin()));
428 } else if ((seq_size==1) &&
429 is_exactly_a<add>((*seq.begin()).rest) &&
430 ex_to<numeric>((*seq.begin()).coeff).is_equal(*_num1_p)) {
431 // *(+(x,y,...);c) -> +(*(x,c),*(y,c),...) (c numeric(), no powers of +())
432 const add & addref = ex_to<add>((*seq.begin()).rest);
433 std::auto_ptr<epvector> distrseq(new epvector);
434 distrseq->reserve(addref.seq.size());
435 epvector::const_iterator i = addref.seq.begin(), end = addref.seq.end();
437 distrseq->push_back(addref.combine_pair_with_coeff_to_pair(*i, overall_coeff));
440 return (new add(distrseq,
441 ex_to<numeric>(addref.overall_coeff).
442 mul_dyn(ex_to<numeric>(overall_coeff)))
443 )->setflag(status_flags::dynallocated | status_flags::evaluated);
444 } else if ((seq_size >= 2) && (! (flags & status_flags::expanded))) {
445 // Strip the content and the unit part from each term. Thus
446 // things like (-x+a)*(3*x-3*a) automagically turn into - 3*(x-a)2
448 epvector::const_iterator last = seq.end();
449 epvector::const_iterator i = seq.begin();
450 epvector::const_iterator j = seq.begin();
451 std::auto_ptr<epvector> s(new epvector);
452 numeric oc = *_num1_p;
453 bool something_changed = false;
455 if (likely(! (is_a<add>(i->rest) && i->coeff.is_equal(_ex1)))) {
456 // power::eval has such a rule, no need to handle powers here
461 // XXX: What is the best way to check if the polynomial is a primitive?
462 numeric c = i->rest.integer_content();
463 const numeric lead_coeff =
464 ex_to<numeric>(ex_to<add>(i->rest).seq.begin()->coeff).div(c);
465 const bool canonicalizable = lead_coeff.is_integer();
467 // XXX: The main variable is chosen in a random way, so this code
468 // does NOT transform the term into the canonical form (thus, in some
469 // very unlucky event it can even loop forever). Hopefully the main
470 // variable will be the same for all terms in *this
471 const bool unit_normal = lead_coeff.is_pos_integer();
472 if (likely((c == *_num1_p) && ((! canonicalizable) || unit_normal))) {
477 if (! something_changed) {
478 s->reserve(seq_size);
479 something_changed = true;
482 while ((j!=i) && (j!=last)) {
488 c = c.mul(*_num_1_p);
492 // divide add by the number in place to save at least 2 .eval() calls
493 const add& addref = ex_to<add>(i->rest);
494 add* primitive = new add(addref);
495 primitive->setflag(status_flags::dynallocated);
496 primitive->clearflag(status_flags::hash_calculated);
497 primitive->overall_coeff = ex_to<numeric>(primitive->overall_coeff).div_dyn(c);
498 for (epvector::iterator ai = primitive->seq.begin();
499 ai != primitive->seq.end(); ++ai)
500 ai->coeff = ex_to<numeric>(ai->coeff).div_dyn(c);
502 s->push_back(expair(*primitive, _ex1));
507 if (something_changed) {
512 return (new mul(s, ex_to<numeric>(overall_coeff).mul_dyn(oc))
513 )->setflag(status_flags::dynallocated);
520 ex mul::evalf(int level) const
523 return mul(seq,overall_coeff);
525 if (level==-max_recursion_level)
526 throw(std::runtime_error("max recursion level reached"));
528 std::auto_ptr<epvector> s(new epvector);
529 s->reserve(seq.size());
532 epvector::const_iterator i = seq.begin(), end = seq.end();
534 s->push_back(combine_ex_with_coeff_to_pair(i->rest.evalf(level),
538 return mul(s, overall_coeff.evalf(level));
541 void mul::find_real_imag(ex & rp, ex & ip) const
543 rp = overall_coeff.real_part();
544 ip = overall_coeff.imag_part();
545 for (epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i) {
546 ex factor = recombine_pair_to_ex(*i);
547 ex new_rp = factor.real_part();
548 ex new_ip = factor.imag_part();
549 if(new_ip.is_zero()) {
553 ex temp = rp*new_rp - ip*new_ip;
554 ip = ip*new_rp + rp*new_ip;
562 ex mul::real_part() const
565 find_real_imag(rp, ip);
569 ex mul::imag_part() const
572 find_real_imag(rp, ip);
576 ex mul::evalm() const
579 if (seq.size() == 1 && seq[0].coeff.is_equal(_ex1)
580 && is_a<matrix>(seq[0].rest))
581 return ex_to<matrix>(seq[0].rest).mul(ex_to<numeric>(overall_coeff));
583 // Evaluate children first, look whether there are any matrices at all
584 // (there can be either no matrices or one matrix; if there were more
585 // than one matrix, it would be a non-commutative product)
586 std::auto_ptr<epvector> s(new epvector);
587 s->reserve(seq.size());
589 bool have_matrix = false;
590 epvector::iterator the_matrix;
592 epvector::const_iterator i = seq.begin(), end = seq.end();
594 const ex &m = recombine_pair_to_ex(*i).evalm();
595 s->push_back(split_ex_to_pair(m));
596 if (is_a<matrix>(m)) {
598 the_matrix = s->end() - 1;
605 // The product contained a matrix. We will multiply all other factors
607 matrix m = ex_to<matrix>(the_matrix->rest);
608 s->erase(the_matrix);
609 ex scalar = (new mul(s, overall_coeff))->setflag(status_flags::dynallocated);
610 return m.mul_scalar(scalar);
613 return (new mul(s, overall_coeff))->setflag(status_flags::dynallocated);
616 ex mul::eval_ncmul(const exvector & v) const
619 return inherited::eval_ncmul(v);
621 // Find first noncommutative element and call its eval_ncmul()
622 epvector::const_iterator i = seq.begin(), end = seq.end();
624 if (i->rest.return_type() == return_types::noncommutative)
625 return i->rest.eval_ncmul(v);
628 return inherited::eval_ncmul(v);
631 bool tryfactsubs(const ex & origfactor, const ex & patternfactor, int & nummatches, exmap& repls)
637 if (is_exactly_a<power>(origfactor) && origfactor.op(1).info(info_flags::integer)) {
638 origbase = origfactor.op(0);
639 int expon = ex_to<numeric>(origfactor.op(1)).to_int();
640 origexponent = expon > 0 ? expon : -expon;
641 origexpsign = expon > 0 ? 1 : -1;
643 origbase = origfactor;
652 if (is_exactly_a<power>(patternfactor) && patternfactor.op(1).info(info_flags::integer)) {
653 patternbase = patternfactor.op(0);
654 int expon = ex_to<numeric>(patternfactor.op(1)).to_int();
655 patternexponent = expon > 0 ? expon : -expon;
656 patternexpsign = expon > 0 ? 1 : -1;
658 patternbase = patternfactor;
663 exmap saverepls = repls;
664 if (origexponent < patternexponent || origexpsign != patternexpsign || !origbase.match(patternbase,saverepls))
668 int newnummatches = origexponent / patternexponent;
669 if (newnummatches < nummatches)
670 nummatches = newnummatches;
674 /** Checks wheter e matches to the pattern pat and the (possibly to be updated)
675 * list of replacements repls. This matching is in the sense of algebraic
676 * substitutions. Matching starts with pat.op(factor) of the pattern because
677 * the factors before this one have already been matched. The (possibly
678 * updated) number of matches is in nummatches. subsed[i] is true for factors
679 * that already have been replaced by previous substitutions and matched[i]
680 * is true for factors that have been matched by the current match.
682 bool algebraic_match_mul_with_mul(const mul &e, const ex &pat, exmap& repls,
683 int factor, int &nummatches, const std::vector<bool> &subsed,
684 std::vector<bool> &matched)
686 if (factor == pat.nops())
689 for (size_t i=0; i<e.nops(); ++i) {
690 if(subsed[i] || matched[i])
692 exmap newrepls = repls;
693 int newnummatches = nummatches;
694 if (tryfactsubs(e.op(i), pat.op(factor), newnummatches, newrepls)) {
696 if (algebraic_match_mul_with_mul(e, pat, newrepls, factor+1,
697 newnummatches, subsed, matched)) {
699 nummatches = newnummatches;
710 bool mul::has(const ex & pattern, unsigned options) const
712 if(!(options&has_options::algebraic))
713 return basic::has(pattern,options);
714 if(is_a<mul>(pattern)) {
716 int nummatches = std::numeric_limits<int>::max();
717 std::vector<bool> subsed(seq.size(), false);
718 std::vector<bool> matched(seq.size(), false);
719 if(algebraic_match_mul_with_mul(*this, pattern, repls, 0, nummatches,
723 return basic::has(pattern, options);
726 ex mul::algebraic_subs_mul(const exmap & m, unsigned options) const
728 std::vector<bool> subsed(seq.size(), false);
729 exvector subsresult(seq.size());
733 for (exmap::const_iterator it = m.begin(); it != m.end(); ++it) {
735 if (is_exactly_a<mul>(it->first)) {
737 int nummatches = std::numeric_limits<int>::max();
738 std::vector<bool> currsubsed(seq.size(), false);
741 if(!algebraic_match_mul_with_mul(*this, it->first, repls, 0, nummatches, subsed, currsubsed))
744 for (size_t j=0; j<subsed.size(); j++)
748 = it->first.subs(repls, subs_options::no_pattern);
749 divide_by *= power(subsed_pattern, nummatches);
751 = it->second.subs(repls, subs_options::no_pattern);
752 multiply_by *= power(subsed_result, nummatches);
757 for (size_t j=0; j<this->nops(); j++) {
758 int nummatches = std::numeric_limits<int>::max();
760 if (!subsed[j] && tryfactsubs(op(j), it->first, nummatches, repls)){
763 = it->first.subs(repls, subs_options::no_pattern);
764 divide_by *= power(subsed_pattern, nummatches);
766 = it->second.subs(repls, subs_options::no_pattern);
767 multiply_by *= power(subsed_result, nummatches);
773 bool subsfound = false;
774 for (size_t i=0; i<subsed.size(); i++) {
781 return subs_one_level(m, options | subs_options::algebraic);
783 return ((*this)/divide_by)*multiply_by;
788 /** Implementation of ex::diff() for a product. It applies the product rule.
790 ex mul::derivative(const symbol & s) const
792 size_t num = seq.size();
796 // D(a*b*c) = D(a)*b*c + a*D(b)*c + a*b*D(c)
797 epvector mulseq = seq;
798 epvector::const_iterator i = seq.begin(), end = seq.end();
799 epvector::iterator i2 = mulseq.begin();
801 expair ep = split_ex_to_pair(power(i->rest, i->coeff - _ex1) *
804 addseq.push_back((new mul(mulseq, overall_coeff * i->coeff))->setflag(status_flags::dynallocated));
808 return (new add(addseq))->setflag(status_flags::dynallocated);
811 int mul::compare_same_type(const basic & other) const
813 return inherited::compare_same_type(other);
816 unsigned mul::return_type() const
819 // mul without factors: should not happen, but commutates
820 return return_types::commutative;
823 bool all_commutative = true;
824 epvector::const_iterator noncommutative_element; // point to first found nc element
826 epvector::const_iterator i = seq.begin(), end = seq.end();
828 unsigned rt = i->rest.return_type();
829 if (rt == return_types::noncommutative_composite)
830 return rt; // one ncc -> mul also ncc
831 if ((rt == return_types::noncommutative) && (all_commutative)) {
832 // first nc element found, remember position
833 noncommutative_element = i;
834 all_commutative = false;
836 if ((rt == return_types::noncommutative) && (!all_commutative)) {
837 // another nc element found, compare type_infos
838 if (noncommutative_element->rest.return_type_tinfo() != i->rest.return_type_tinfo()) {
839 // different types -> mul is ncc
840 return return_types::noncommutative_composite;
845 // all factors checked
846 return all_commutative ? return_types::commutative : return_types::noncommutative;
849 return_type_t mul::return_type_tinfo() const
852 return make_return_type_t<mul>(); // mul without factors: should not happen
854 // return type_info of first noncommutative element
855 epvector::const_iterator i = seq.begin(), end = seq.end();
857 if (i->rest.return_type() == return_types::noncommutative)
858 return i->rest.return_type_tinfo();
861 // no noncommutative element found, should not happen
862 return make_return_type_t<mul>();
865 ex mul::thisexpairseq(const epvector & v, const ex & oc, bool do_index_renaming) const
867 return (new mul(v, oc, do_index_renaming))->setflag(status_flags::dynallocated);
870 ex mul::thisexpairseq(std::auto_ptr<epvector> vp, const ex & oc, bool do_index_renaming) const
872 return (new mul(vp, oc, do_index_renaming))->setflag(status_flags::dynallocated);
875 expair mul::split_ex_to_pair(const ex & e) const
877 if (is_exactly_a<power>(e)) {
878 const power & powerref = ex_to<power>(e);
879 if (is_exactly_a<numeric>(powerref.exponent))
880 return expair(powerref.basis,powerref.exponent);
882 return expair(e,_ex1);
885 expair mul::combine_ex_with_coeff_to_pair(const ex & e,
888 // to avoid duplication of power simplification rules,
889 // we create a temporary power object
890 // otherwise it would be hard to correctly evaluate
891 // expression like (4^(1/3))^(3/2)
892 if (c.is_equal(_ex1))
893 return split_ex_to_pair(e);
895 return split_ex_to_pair(power(e,c));
898 expair mul::combine_pair_with_coeff_to_pair(const expair & p,
901 // to avoid duplication of power simplification rules,
902 // we create a temporary power object
903 // otherwise it would be hard to correctly evaluate
904 // expression like (4^(1/3))^(3/2)
905 if (c.is_equal(_ex1))
908 return split_ex_to_pair(power(recombine_pair_to_ex(p),c));
911 ex mul::recombine_pair_to_ex(const expair & p) const
913 if (ex_to<numeric>(p.coeff).is_equal(*_num1_p))
916 return (new power(p.rest,p.coeff))->setflag(status_flags::dynallocated);
919 bool mul::expair_needs_further_processing(epp it)
921 if (is_exactly_a<mul>(it->rest) &&
922 ex_to<numeric>(it->coeff).is_integer()) {
923 // combined pair is product with integer power -> expand it
924 *it = split_ex_to_pair(recombine_pair_to_ex(*it));
927 if (is_exactly_a<numeric>(it->rest)) {
928 expair ep = split_ex_to_pair(recombine_pair_to_ex(*it));
929 if (!ep.is_equal(*it)) {
930 // combined pair is a numeric power which can be simplified
934 if (it->coeff.is_equal(_ex1)) {
935 // combined pair has coeff 1 and must be moved to the end
942 ex mul::default_overall_coeff() const
947 void mul::combine_overall_coeff(const ex & c)
949 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
950 GINAC_ASSERT(is_exactly_a<numeric>(c));
951 overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c));
954 void mul::combine_overall_coeff(const ex & c1, const ex & c2)
956 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
957 GINAC_ASSERT(is_exactly_a<numeric>(c1));
958 GINAC_ASSERT(is_exactly_a<numeric>(c2));
959 overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c1).power(ex_to<numeric>(c2)));
962 bool mul::can_make_flat(const expair & p) const
964 GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
965 // this assertion will probably fail somewhere
966 // it would require a more careful make_flat, obeying the power laws
967 // probably should return true only if p.coeff is integer
968 return ex_to<numeric>(p.coeff).is_equal(*_num1_p);
971 bool mul::can_be_further_expanded(const ex & e)
973 if (is_exactly_a<mul>(e)) {
974 for (epvector::const_iterator cit = ex_to<mul>(e).seq.begin(); cit != ex_to<mul>(e).seq.end(); ++cit) {
975 if (is_exactly_a<add>(cit->rest) && cit->coeff.info(info_flags::posint))
978 } else if (is_exactly_a<power>(e)) {
979 if (is_exactly_a<add>(e.op(0)) && e.op(1).info(info_flags::posint))
985 ex mul::expand(unsigned options) const
988 // trivial case: expanding the monomial (~ 30% of all calls)
989 epvector::const_iterator i = seq.begin(), seq_end = seq.end();
990 while ((i != seq.end()) && is_a<symbol>(i->rest) && i->coeff.info(info_flags::integer))
993 setflag(status_flags::expanded);
998 // do not rename indices if the object has no indices at all
999 if ((!(options & expand_options::expand_rename_idx)) &&
1000 this->info(info_flags::has_indices))
1001 options |= expand_options::expand_rename_idx;
1003 const bool skip_idx_rename = !(options & expand_options::expand_rename_idx);
1005 // First, expand the children
1006 std::auto_ptr<epvector> expanded_seqp = expandchildren(options);
1007 const epvector & expanded_seq = (expanded_seqp.get() ? *expanded_seqp : seq);
1009 // Now, look for all the factors that are sums and multiply each one out
1010 // with the next one that is found while collecting the factors which are
1012 ex last_expanded = _ex1;
1015 non_adds.reserve(expanded_seq.size());
1017 for (epvector::const_iterator cit = expanded_seq.begin(); cit != expanded_seq.end(); ++cit) {
1018 if (is_exactly_a<add>(cit->rest) &&
1019 (cit->coeff.is_equal(_ex1))) {
1020 if (is_exactly_a<add>(last_expanded)) {
1022 // Expand a product of two sums, aggressive version.
1023 // Caring for the overall coefficients in separate loops can
1024 // sometimes give a performance gain of up to 15%!
1026 const int sizedifference = ex_to<add>(last_expanded).seq.size()-ex_to<add>(cit->rest).seq.size();
1027 // add2 is for the inner loop and should be the bigger of the two sums
1028 // in the presence of asymptotically good sorting:
1029 const add& add1 = (sizedifference<0 ? ex_to<add>(last_expanded) : ex_to<add>(cit->rest));
1030 const add& add2 = (sizedifference<0 ? ex_to<add>(cit->rest) : ex_to<add>(last_expanded));
1031 const epvector::const_iterator add1begin = add1.seq.begin();
1032 const epvector::const_iterator add1end = add1.seq.end();
1033 const epvector::const_iterator add2begin = add2.seq.begin();
1034 const epvector::const_iterator add2end = add2.seq.end();
1036 distrseq.reserve(add1.seq.size()+add2.seq.size());
1038 // Multiply add2 with the overall coefficient of add1 and append it to distrseq:
1039 if (!add1.overall_coeff.is_zero()) {
1040 if (add1.overall_coeff.is_equal(_ex1))
1041 distrseq.insert(distrseq.end(),add2begin,add2end);
1043 for (epvector::const_iterator i=add2begin; i!=add2end; ++i)
1044 distrseq.push_back(expair(i->rest, ex_to<numeric>(i->coeff).mul_dyn(ex_to<numeric>(add1.overall_coeff))));
1047 // Multiply add1 with the overall coefficient of add2 and append it to distrseq:
1048 if (!add2.overall_coeff.is_zero()) {
1049 if (add2.overall_coeff.is_equal(_ex1))
1050 distrseq.insert(distrseq.end(),add1begin,add1end);
1052 for (epvector::const_iterator i=add1begin; i!=add1end; ++i)
1053 distrseq.push_back(expair(i->rest, ex_to<numeric>(i->coeff).mul_dyn(ex_to<numeric>(add2.overall_coeff))));
1056 // Compute the new overall coefficient and put it together:
1057 ex tmp_accu = (new add(distrseq, add1.overall_coeff*add2.overall_coeff))->setflag(status_flags::dynallocated);
1059 exvector add1_dummy_indices, add2_dummy_indices, add_indices;
1062 if (!skip_idx_rename) {
1063 for (epvector::const_iterator i=add1begin; i!=add1end; ++i) {
1064 add_indices = get_all_dummy_indices_safely(i->rest);
1065 add1_dummy_indices.insert(add1_dummy_indices.end(), add_indices.begin(), add_indices.end());
1067 for (epvector::const_iterator i=add2begin; i!=add2end; ++i) {
1068 add_indices = get_all_dummy_indices_safely(i->rest);
1069 add2_dummy_indices.insert(add2_dummy_indices.end(), add_indices.begin(), add_indices.end());
1072 sort(add1_dummy_indices.begin(), add1_dummy_indices.end(), ex_is_less());
1073 sort(add2_dummy_indices.begin(), add2_dummy_indices.end(), ex_is_less());
1074 dummy_subs = rename_dummy_indices_uniquely(add1_dummy_indices, add2_dummy_indices);
1077 // Multiply explicitly all non-numeric terms of add1 and add2:
1078 for (epvector::const_iterator i2=add2begin; i2!=add2end; ++i2) {
1079 // We really have to combine terms here in order to compactify
1080 // the result. Otherwise it would become waayy tooo bigg.
1081 numeric oc(*_num0_p);
1083 distrseq2.reserve(add1.seq.size());
1084 const ex i2_new = (skip_idx_rename || (dummy_subs.op(0).nops() == 0) ?
1086 i2->rest.subs(ex_to<lst>(dummy_subs.op(0)),
1087 ex_to<lst>(dummy_subs.op(1)), subs_options::no_pattern));
1088 for (epvector::const_iterator i1=add1begin; i1!=add1end; ++i1) {
1089 // Don't push_back expairs which might have a rest that evaluates to a numeric,
1090 // since that would violate an invariant of expairseq:
1091 const ex rest = (new mul(i1->rest, i2_new))->setflag(status_flags::dynallocated);
1092 if (is_exactly_a<numeric>(rest)) {
1093 oc += ex_to<numeric>(rest).mul(ex_to<numeric>(i1->coeff).mul(ex_to<numeric>(i2->coeff)));
1095 distrseq2.push_back(expair(rest, ex_to<numeric>(i1->coeff).mul_dyn(ex_to<numeric>(i2->coeff))));
1098 tmp_accu += (new add(distrseq2, oc))->setflag(status_flags::dynallocated);
1100 last_expanded = tmp_accu;
1102 if (!last_expanded.is_equal(_ex1))
1103 non_adds.push_back(split_ex_to_pair(last_expanded));
1104 last_expanded = cit->rest;
1108 non_adds.push_back(*cit);
1112 // Now the only remaining thing to do is to multiply the factors which
1113 // were not sums into the "last_expanded" sum
1114 if (is_exactly_a<add>(last_expanded)) {
1115 size_t n = last_expanded.nops();
1117 distrseq.reserve(n);
1119 if (! skip_idx_rename) {
1120 va = get_all_dummy_indices_safely(mul(non_adds));
1121 sort(va.begin(), va.end(), ex_is_less());
1124 for (size_t i=0; i<n; ++i) {
1125 epvector factors = non_adds;
1126 if (skip_idx_rename)
1127 factors.push_back(split_ex_to_pair(last_expanded.op(i)));
1129 factors.push_back(split_ex_to_pair(rename_dummy_indices_uniquely(va, last_expanded.op(i))));
1130 ex term = (new mul(factors, overall_coeff))->setflag(status_flags::dynallocated);
1131 if (can_be_further_expanded(term)) {
1132 distrseq.push_back(term.expand());
1135 ex_to<basic>(term).setflag(status_flags::expanded);
1136 distrseq.push_back(term);
1140 return ((new add(distrseq))->
1141 setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0)));
1144 non_adds.push_back(split_ex_to_pair(last_expanded));
1145 ex result = (new mul(non_adds, overall_coeff))->setflag(status_flags::dynallocated);
1146 if (can_be_further_expanded(result)) {
1147 return result.expand();
1150 ex_to<basic>(result).setflag(status_flags::expanded);
1157 // new virtual functions which can be overridden by derived classes
1163 // non-virtual functions in this class
1167 /** Member-wise expand the expairs representing this sequence. This must be
1168 * overridden from expairseq::expandchildren() and done iteratively in order
1169 * to allow for early cancallations and thus safe memory.
1171 * @see mul::expand()
1172 * @return pointer to epvector containing expanded representation or zero
1173 * pointer, if sequence is unchanged. */
1174 std::auto_ptr<epvector> mul::expandchildren(unsigned options) const
1176 const epvector::const_iterator last = seq.end();
1177 epvector::const_iterator cit = seq.begin();
1179 const ex & factor = recombine_pair_to_ex(*cit);
1180 const ex & expanded_factor = factor.expand(options);
1181 if (!are_ex_trivially_equal(factor,expanded_factor)) {
1183 // something changed, copy seq, eval and return it
1184 std::auto_ptr<epvector> s(new epvector);
1185 s->reserve(seq.size());
1187 // copy parts of seq which are known not to have changed
1188 epvector::const_iterator cit2 = seq.begin();
1190 s->push_back(*cit2);
1194 // copy first changed element
1195 s->push_back(split_ex_to_pair(expanded_factor));
1199 while (cit2!=last) {
1200 s->push_back(split_ex_to_pair(recombine_pair_to_ex(*cit2).expand(options)));
1208 return std::auto_ptr<epvector>(0); // nothing has changed
1211 GINAC_BIND_UNARCHIVER(mul);
1213 } // namespace GiNaC