3 * Implementation of GiNaC's products of expressions. */
6 * GiNaC Copyright (C) 1999-2015 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
26 #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(epvector && vp, const ex & oc, bool do_index_renaming)
95 construct_from_epvector(std::move(vp), do_index_renaming);
96 GINAC_ASSERT(is_canonical());
99 mul::mul(const ex & lh, const ex & mh, const ex & rh)
103 factors.push_back(lh);
104 factors.push_back(mh);
105 factors.push_back(rh);
106 overall_coeff = _ex1;
107 construct_from_exvector(factors);
108 GINAC_ASSERT(is_canonical());
116 // functions overriding virtual functions from base classes
119 void mul::print_overall_coeff(const print_context & c, const char *mul_sym) const
121 const numeric &coeff = ex_to<numeric>(overall_coeff);
122 if (coeff.csgn() == -1)
124 if (!coeff.is_equal(*_num1_p) &&
125 !coeff.is_equal(*_num_1_p)) {
126 if (coeff.is_rational()) {
127 if (coeff.is_negative())
132 if (coeff.csgn() == -1)
133 (-coeff).print(c, precedence());
135 coeff.print(c, precedence());
141 void mul::do_print(const print_context & c, unsigned level) const
143 if (precedence() <= level)
146 print_overall_coeff(c, "*");
149 for (auto & it : seq) {
154 recombine_pair_to_ex(it).print(c, precedence());
157 if (precedence() <= level)
161 void mul::do_print_latex(const print_latex & c, unsigned level) const
163 if (precedence() <= level)
166 print_overall_coeff(c, " ");
168 // Separate factors into those with negative numeric exponent
170 exvector neg_powers, others;
171 for (auto & it : seq) {
172 GINAC_ASSERT(is_exactly_a<numeric>(it.coeff));
173 if (ex_to<numeric>(it.coeff).is_negative())
174 neg_powers.push_back(recombine_pair_to_ex(expair(it.rest, -it.coeff)));
176 others.push_back(recombine_pair_to_ex(it));
179 if (!neg_powers.empty()) {
181 // Factors with negative exponent are printed as a fraction
183 mul(others).eval().print(c);
185 mul(neg_powers).eval().print(c);
190 // All other factors are printed in the ordinary way
191 for (auto & vit : others) {
193 vit.print(c, precedence());
197 if (precedence() <= level)
201 void mul::do_print_csrc(const print_csrc & c, unsigned level) const
203 if (precedence() <= level)
206 if (!overall_coeff.is_equal(_ex1)) {
207 if (overall_coeff.is_equal(_ex_1))
210 overall_coeff.print(c, precedence());
215 // Print arguments, separated by "*" or "/"
216 auto it = seq.begin(), itend = seq.end();
217 while (it != itend) {
219 // If the first argument is a negative integer power, it gets printed as "1.0/<expr>"
220 bool needclosingparenthesis = false;
221 if (it == seq.begin() && it->coeff.info(info_flags::negint)) {
222 if (is_a<print_csrc_cl_N>(c)) {
224 needclosingparenthesis = true;
229 // If the exponent is 1 or -1, it is left out
230 if (it->coeff.is_equal(_ex1) || it->coeff.is_equal(_ex_1))
231 it->rest.print(c, precedence());
232 else if (it->coeff.info(info_flags::negint))
233 ex(power(it->rest, -ex_to<numeric>(it->coeff))).print(c, level);
235 ex(power(it->rest, ex_to<numeric>(it->coeff))).print(c, level);
237 if (needclosingparenthesis)
240 // Separator is "/" for negative integer powers, "*" otherwise
243 if (it->coeff.info(info_flags::negint))
250 if (precedence() <= level)
254 void mul::do_print_python_repr(const print_python_repr & c, unsigned level) const
256 c.s << class_name() << '(';
258 for (size_t i=1; i<nops(); ++i) {
265 bool mul::info(unsigned inf) const
268 case info_flags::polynomial:
269 case info_flags::integer_polynomial:
270 case info_flags::cinteger_polynomial:
271 case info_flags::rational_polynomial:
272 case info_flags::real:
273 case info_flags::rational:
274 case info_flags::integer:
275 case info_flags::crational:
276 case info_flags::cinteger:
277 case info_flags::even:
278 case info_flags::crational_polynomial:
279 case info_flags::rational_function: {
280 for (auto & it : seq) {
281 if (!recombine_pair_to_ex(it).info(inf))
284 if (overall_coeff.is_equal(*_num1_p) && inf == info_flags::even)
286 return overall_coeff.info(inf);
288 case info_flags::algebraic: {
289 for (auto & it : seq) {
290 if (recombine_pair_to_ex(it).info(inf))
295 case info_flags::positive:
296 case info_flags::negative: {
297 if ((inf==info_flags::positive) && (flags & status_flags::is_positive))
299 else if ((inf==info_flags::negative) && (flags & status_flags::is_negative))
301 if (flags & status_flags::purely_indefinite)
305 for (auto & it : seq) {
306 const ex& factor = recombine_pair_to_ex(it);
307 if (factor.info(info_flags::positive))
309 else if (factor.info(info_flags::negative))
314 if (overall_coeff.info(info_flags::negative))
316 setflag(pos ? status_flags::is_positive : status_flags::is_negative);
317 return (inf == info_flags::positive? pos : !pos);
319 case info_flags::nonnegative: {
320 if (flags & status_flags::is_positive)
323 for (auto & it : seq) {
324 const ex& factor = recombine_pair_to_ex(it);
325 if (factor.info(info_flags::nonnegative) || factor.info(info_flags::positive))
327 else if (factor.info(info_flags::negative))
332 return (overall_coeff.info(info_flags::negative)? !pos : pos);
334 case info_flags::posint:
335 case info_flags::negint: {
337 for (auto & it : seq) {
338 const ex& factor = recombine_pair_to_ex(it);
339 if (factor.info(info_flags::posint))
341 else if (factor.info(info_flags::negint))
346 if (overall_coeff.info(info_flags::negint))
348 else if (!overall_coeff.info(info_flags::posint))
350 return (inf ==info_flags::posint? pos : !pos);
352 case info_flags::nonnegint: {
354 for (auto & it : seq) {
355 const ex& factor = recombine_pair_to_ex(it);
356 if (factor.info(info_flags::nonnegint) || factor.info(info_flags::posint))
358 else if (factor.info(info_flags::negint))
363 if (overall_coeff.info(info_flags::negint))
365 else if (!overall_coeff.info(info_flags::posint))
369 case info_flags::indefinite: {
370 if (flags & status_flags::purely_indefinite)
372 if (flags & (status_flags::is_positive | status_flags::is_negative))
374 for (auto & it : seq) {
375 const ex& term = recombine_pair_to_ex(it);
376 if (term.info(info_flags::positive) || term.info(info_flags::negative))
379 setflag(status_flags::purely_indefinite);
383 return inherited::info(inf);
386 bool mul::is_polynomial(const ex & var) const
388 for (auto & it : seq) {
389 if (!it.rest.is_polynomial(var) ||
390 (it.rest.has(var) && !it.coeff.info(info_flags::nonnegint))) {
397 int mul::degree(const ex & s) const
399 // Sum up degrees of factors
401 for (auto & it : seq) {
402 if (ex_to<numeric>(it.coeff).is_integer())
403 deg_sum += recombine_pair_to_ex(it).degree(s);
406 throw std::runtime_error("mul::degree() undefined degree because of non-integer exponent");
412 int mul::ldegree(const ex & s) const
414 // Sum up degrees of factors
416 for (auto & it : seq) {
417 if (ex_to<numeric>(it.coeff).is_integer())
418 deg_sum += recombine_pair_to_ex(it).ldegree(s);
421 throw std::runtime_error("mul::ldegree() undefined degree because of non-integer exponent");
427 ex mul::coeff(const ex & s, int n) const
430 coeffseq.reserve(seq.size()+1);
433 // product of individual coeffs
434 // if a non-zero power of s is found, the resulting product will be 0
435 for (auto & it : seq)
436 coeffseq.push_back(recombine_pair_to_ex(it).coeff(s,n));
437 coeffseq.push_back(overall_coeff);
438 return dynallocate<mul>(coeffseq);
441 bool coeff_found = false;
442 for (auto & it : seq) {
443 ex t = recombine_pair_to_ex(it);
444 ex c = t.coeff(s, n);
446 coeffseq.push_back(c);
449 coeffseq.push_back(t);
453 coeffseq.push_back(overall_coeff);
454 return dynallocate<mul>(coeffseq);
460 /** Perform automatic term rewriting rules in this class. In the following
461 * x, x1, x2,... stand for a symbolic variables of type ex and c, c1, c2...
462 * stand for such expressions that contain a plain number.
464 * - *(+(x1,x2,...);c) -> *(+(*(x1,c),*(x2,c),...))
468 * @param level cut-off in recursive evaluation */
469 ex mul::eval(int level) const
471 epvector evaled = evalchildren(level);
472 if (unlikely(!evaled.empty())) {
473 // do more evaluation later
474 return dynallocate<mul>(std::move(evaled), overall_coeff);
477 if (flags & status_flags::evaluated) {
478 GINAC_ASSERT(seq.size()>0);
479 GINAC_ASSERT(seq.size()>1 || !overall_coeff.is_equal(_ex1));
483 size_t seq_size = seq.size();
484 if (overall_coeff.is_zero()) {
487 } else if (seq_size==0) {
489 return overall_coeff;
490 } else if (seq_size==1 && overall_coeff.is_equal(_ex1)) {
492 return recombine_pair_to_ex(*(seq.begin()));
493 } else if ((seq_size==1) &&
494 is_exactly_a<add>((*seq.begin()).rest) &&
495 ex_to<numeric>((*seq.begin()).coeff).is_equal(*_num1_p)) {
496 // *(+(x,y,...);c) -> +(*(x,c),*(y,c),...) (c numeric(), no powers of +())
497 const add & addref = ex_to<add>((*seq.begin()).rest);
499 distrseq.reserve(addref.seq.size());
500 for (auto & it : addref.seq) {
501 distrseq.push_back(addref.combine_pair_with_coeff_to_pair(it, overall_coeff));
503 return dynallocate<add>(std::move(distrseq),
504 ex_to<numeric>(addref.overall_coeff).mul_dyn(ex_to<numeric>(overall_coeff)))
505 .setflag(status_flags::evaluated);
506 } else if ((seq_size >= 2) && (! (flags & status_flags::expanded))) {
507 // Strip the content and the unit part from each term. Thus
508 // things like (-x+a)*(3*x-3*a) automagically turn into - 3*(x-a)^2
510 auto i = seq.begin(), last = seq.end();
511 auto j = seq.begin();
513 numeric oc = *_num1_p;
514 bool something_changed = false;
516 if (likely(! (is_a<add>(i->rest) && i->coeff.is_equal(_ex1)))) {
517 // power::eval has such a rule, no need to handle powers here
522 // XXX: What is the best way to check if the polynomial is a primitive?
523 numeric c = i->rest.integer_content();
524 const numeric lead_coeff =
525 ex_to<numeric>(ex_to<add>(i->rest).seq.begin()->coeff).div(c);
526 const bool canonicalizable = lead_coeff.is_integer();
528 // XXX: The main variable is chosen in a random way, so this code
529 // does NOT transform the term into the canonical form (thus, in some
530 // very unlucky event it can even loop forever). Hopefully the main
531 // variable will be the same for all terms in *this
532 const bool unit_normal = lead_coeff.is_pos_integer();
533 if (likely((c == *_num1_p) && ((! canonicalizable) || unit_normal))) {
538 if (! something_changed) {
540 something_changed = true;
543 while ((j!=i) && (j!=last)) {
549 c = c.mul(*_num_1_p);
553 // divide add by the number in place to save at least 2 .eval() calls
554 const add& addref = ex_to<add>(i->rest);
555 add & primitive = dynallocate<add>(addref);
556 primitive.clearflag(status_flags::hash_calculated);
557 primitive.overall_coeff = ex_to<numeric>(primitive.overall_coeff).div_dyn(c);
558 for (epvector::iterator ai = primitive.seq.begin(); ai != primitive.seq.end(); ++ai)
559 ai->coeff = ex_to<numeric>(ai->coeff).div_dyn(c);
561 s.push_back(expair(primitive, _ex1));
566 if (something_changed) {
571 return dynallocate<mul>(std::move(s), ex_to<numeric>(overall_coeff).mul_dyn(oc));
578 ex mul::evalf(int level) const
581 return mul(seq,overall_coeff);
583 if (level==-max_recursion_level)
584 throw(std::runtime_error("max recursion level reached"));
587 s.reserve(seq.size());
590 for (auto & it : seq) {
591 s.push_back(combine_ex_with_coeff_to_pair(it.rest.evalf(level),
594 return mul(std::move(s), overall_coeff.evalf(level));
597 void mul::find_real_imag(ex & rp, ex & ip) const
599 rp = overall_coeff.real_part();
600 ip = overall_coeff.imag_part();
601 for (auto & it : seq) {
602 ex factor = recombine_pair_to_ex(it);
603 ex new_rp = factor.real_part();
604 ex new_ip = factor.imag_part();
605 if (new_ip.is_zero()) {
609 ex temp = rp*new_rp - ip*new_ip;
610 ip = ip*new_rp + rp*new_ip;
618 ex mul::real_part() const
621 find_real_imag(rp, ip);
625 ex mul::imag_part() const
628 find_real_imag(rp, ip);
632 ex mul::evalm() const
635 if (seq.size() == 1 && seq[0].coeff.is_equal(_ex1)
636 && is_a<matrix>(seq[0].rest))
637 return ex_to<matrix>(seq[0].rest).mul(ex_to<numeric>(overall_coeff));
639 // Evaluate children first, look whether there are any matrices at all
640 // (there can be either no matrices or one matrix; if there were more
641 // than one matrix, it would be a non-commutative product)
643 s.reserve(seq.size());
645 bool have_matrix = false;
646 epvector::iterator the_matrix;
648 for (auto & it : seq) {
649 const ex &m = recombine_pair_to_ex(it).evalm();
650 s.push_back(split_ex_to_pair(m));
651 if (is_a<matrix>(m)) {
653 the_matrix = s.end() - 1;
659 // The product contained a matrix. We will multiply all other factors
661 matrix m = ex_to<matrix>(the_matrix->rest);
663 ex scalar = dynallocate<mul>(std::move(s), overall_coeff);
664 return m.mul_scalar(scalar);
667 return dynallocate<mul>(std::move(s), overall_coeff);
670 ex mul::eval_ncmul(const exvector & v) const
673 return inherited::eval_ncmul(v);
675 // Find first noncommutative element and call its eval_ncmul()
676 for (auto & it : seq)
677 if (it.rest.return_type() == return_types::noncommutative)
678 return it.rest.eval_ncmul(v);
679 return inherited::eval_ncmul(v);
682 bool tryfactsubs(const ex & origfactor, const ex & patternfactor, int & nummatches, exmap& repls)
688 if (is_exactly_a<power>(origfactor) && origfactor.op(1).info(info_flags::integer)) {
689 origbase = origfactor.op(0);
690 int expon = ex_to<numeric>(origfactor.op(1)).to_int();
691 origexponent = expon > 0 ? expon : -expon;
692 origexpsign = expon > 0 ? 1 : -1;
694 origbase = origfactor;
703 if (is_exactly_a<power>(patternfactor) && patternfactor.op(1).info(info_flags::integer)) {
704 patternbase = patternfactor.op(0);
705 int expon = ex_to<numeric>(patternfactor.op(1)).to_int();
706 patternexponent = expon > 0 ? expon : -expon;
707 patternexpsign = expon > 0 ? 1 : -1;
709 patternbase = patternfactor;
714 exmap saverepls = repls;
715 if (origexponent < patternexponent || origexpsign != patternexpsign || !origbase.match(patternbase,saverepls))
719 int newnummatches = origexponent / patternexponent;
720 if (newnummatches < nummatches)
721 nummatches = newnummatches;
725 /** Checks whether e matches to the pattern pat and the (possibly to be updated)
726 * list of replacements repls. This matching is in the sense of algebraic
727 * substitutions. Matching starts with pat.op(factor) of the pattern because
728 * the factors before this one have already been matched. The (possibly
729 * updated) number of matches is in nummatches. subsed[i] is true for factors
730 * that already have been replaced by previous substitutions and matched[i]
731 * is true for factors that have been matched by the current match.
733 bool algebraic_match_mul_with_mul(const mul &e, const ex &pat, exmap& repls,
734 int factor, int &nummatches, const std::vector<bool> &subsed,
735 std::vector<bool> &matched)
737 GINAC_ASSERT(subsed.size() == e.nops());
738 GINAC_ASSERT(matched.size() == e.nops());
740 if (factor == (int)pat.nops())
743 for (size_t i=0; i<e.nops(); ++i) {
744 if(subsed[i] || matched[i])
746 exmap newrepls = repls;
747 int newnummatches = nummatches;
748 if (tryfactsubs(e.op(i), pat.op(factor), newnummatches, newrepls)) {
750 if (algebraic_match_mul_with_mul(e, pat, newrepls, factor+1,
751 newnummatches, subsed, matched)) {
753 nummatches = newnummatches;
764 bool mul::has(const ex & pattern, unsigned options) const
766 if(!(options & has_options::algebraic))
767 return basic::has(pattern,options);
768 if(is_a<mul>(pattern)) {
770 int nummatches = std::numeric_limits<int>::max();
771 std::vector<bool> subsed(nops(), false);
772 std::vector<bool> matched(nops(), false);
773 if(algebraic_match_mul_with_mul(*this, pattern, repls, 0, nummatches,
777 return basic::has(pattern, options);
780 ex mul::algebraic_subs_mul(const exmap & m, unsigned options) const
782 std::vector<bool> subsed(nops(), false);
786 for (auto & it : m) {
788 if (is_exactly_a<mul>(it.first)) {
790 int nummatches = std::numeric_limits<int>::max();
791 std::vector<bool> currsubsed(nops(), false);
794 if (!algebraic_match_mul_with_mul(*this, it.first, repls, 0, nummatches, subsed, currsubsed))
797 for (size_t j=0; j<subsed.size(); j++)
801 = it.first.subs(repls, subs_options::no_pattern);
802 divide_by *= power(subsed_pattern, nummatches);
804 = it.second.subs(repls, subs_options::no_pattern);
805 multiply_by *= power(subsed_result, nummatches);
810 for (size_t j=0; j<this->nops(); j++) {
811 int nummatches = std::numeric_limits<int>::max();
813 if (!subsed[j] && tryfactsubs(op(j), it.first, nummatches, repls)){
816 = it.first.subs(repls, subs_options::no_pattern);
817 divide_by *= power(subsed_pattern, nummatches);
819 = it.second.subs(repls, subs_options::no_pattern);
820 multiply_by *= power(subsed_result, nummatches);
826 bool subsfound = false;
827 for (size_t i=0; i<subsed.size(); i++) {
834 return subs_one_level(m, options | subs_options::algebraic);
836 return ((*this)/divide_by)*multiply_by;
839 ex mul::conjugate() const
841 // The base class' method is wrong here because we have to be careful at
842 // branch cuts. power::conjugate takes care of that already, so use it.
843 std::unique_ptr<epvector> newepv(nullptr);
844 for (auto i=seq.begin(); i!=seq.end(); ++i) {
846 newepv->push_back(split_ex_to_pair(recombine_pair_to_ex(*i).conjugate()));
849 ex x = recombine_pair_to_ex(*i);
850 ex c = x.conjugate();
854 newepv.reset(new epvector);
855 newepv->reserve(seq.size());
856 for (auto j=seq.begin(); j!=i; ++j) {
857 newepv->push_back(*j);
859 newepv->push_back(split_ex_to_pair(c));
861 ex x = overall_coeff.conjugate();
862 if (!newepv && are_ex_trivially_equal(x, overall_coeff)) {
865 return thisexpairseq(newepv ? std::move(*newepv) : seq, x);
871 /** Implementation of ex::diff() for a product. It applies the product rule.
873 ex mul::derivative(const symbol & s) const
875 size_t num = seq.size();
879 // D(a*b*c) = D(a)*b*c + a*D(b)*c + a*b*D(c)
880 epvector mulseq = seq;
881 auto i = seq.begin(), end = seq.end();
882 auto i2 = mulseq.begin();
884 expair ep = split_ex_to_pair(power(i->rest, i->coeff - _ex1) *
887 addseq.push_back(dynallocate<mul>(mulseq, overall_coeff * i->coeff));
891 return dynallocate<add>(addseq);
894 int mul::compare_same_type(const basic & other) const
896 return inherited::compare_same_type(other);
899 unsigned mul::return_type() const
902 // mul without factors: should not happen, but commutates
903 return return_types::commutative;
906 bool all_commutative = true;
907 epvector::const_iterator noncommutative_element; // point to first found nc element
909 epvector::const_iterator i = seq.begin(), end = seq.end();
911 unsigned rt = i->rest.return_type();
912 if (rt == return_types::noncommutative_composite)
913 return rt; // one ncc -> mul also ncc
914 if ((rt == return_types::noncommutative) && (all_commutative)) {
915 // first nc element found, remember position
916 noncommutative_element = i;
917 all_commutative = false;
919 if ((rt == return_types::noncommutative) && (!all_commutative)) {
920 // another nc element found, compare type_infos
921 if (noncommutative_element->rest.return_type_tinfo() != i->rest.return_type_tinfo()) {
922 // different types -> mul is ncc
923 return return_types::noncommutative_composite;
928 // all factors checked
929 return all_commutative ? return_types::commutative : return_types::noncommutative;
932 return_type_t mul::return_type_tinfo() const
935 return make_return_type_t<mul>(); // mul without factors: should not happen
937 // return type_info of first noncommutative element
938 for (auto & it : seq)
939 if (it.rest.return_type() == return_types::noncommutative)
940 return it.rest.return_type_tinfo();
942 // no noncommutative element found, should not happen
943 return make_return_type_t<mul>();
946 ex mul::thisexpairseq(const epvector & v, const ex & oc, bool do_index_renaming) const
948 return dynallocate<mul>(v, oc, do_index_renaming);
951 ex mul::thisexpairseq(epvector && vp, const ex & oc, bool do_index_renaming) const
953 return dynallocate<mul>(std::move(vp), oc, do_index_renaming);
956 expair mul::split_ex_to_pair(const ex & e) const
958 if (is_exactly_a<power>(e)) {
959 const power & powerref = ex_to<power>(e);
960 if (is_exactly_a<numeric>(powerref.exponent))
961 return expair(powerref.basis,powerref.exponent);
963 return expair(e,_ex1);
966 expair mul::combine_ex_with_coeff_to_pair(const ex & e,
969 // to avoid duplication of power simplification rules,
970 // we create a temporary power object
971 // otherwise it would be hard to correctly evaluate
972 // expression like (4^(1/3))^(3/2)
973 if (c.is_equal(_ex1))
974 return split_ex_to_pair(e);
976 return split_ex_to_pair(power(e,c));
979 expair mul::combine_pair_with_coeff_to_pair(const expair & p,
982 // to avoid duplication of power simplification rules,
983 // we create a temporary power object
984 // otherwise it would be hard to correctly evaluate
985 // expression like (4^(1/3))^(3/2)
986 if (c.is_equal(_ex1))
989 return split_ex_to_pair(power(recombine_pair_to_ex(p),c));
992 ex mul::recombine_pair_to_ex(const expair & p) const
994 if (ex_to<numeric>(p.coeff).is_equal(*_num1_p))
997 return dynallocate<power>(p.rest, p.coeff);
1000 bool mul::expair_needs_further_processing(epp it)
1002 if (is_exactly_a<mul>(it->rest) &&
1003 ex_to<numeric>(it->coeff).is_integer()) {
1004 // combined pair is product with integer power -> expand it
1005 *it = split_ex_to_pair(recombine_pair_to_ex(*it));
1008 if (is_exactly_a<numeric>(it->rest)) {
1009 if (it->coeff.is_equal(_ex1)) {
1010 // pair has coeff 1 and must be moved to the end
1013 expair ep = split_ex_to_pair(recombine_pair_to_ex(*it));
1014 if (!ep.is_equal(*it)) {
1015 // combined pair is a numeric power which can be simplified
1023 ex mul::default_overall_coeff() const
1028 void mul::combine_overall_coeff(const ex & c)
1030 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1031 GINAC_ASSERT(is_exactly_a<numeric>(c));
1032 overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c));
1035 void mul::combine_overall_coeff(const ex & c1, const ex & c2)
1037 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1038 GINAC_ASSERT(is_exactly_a<numeric>(c1));
1039 GINAC_ASSERT(is_exactly_a<numeric>(c2));
1040 overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c1).power(ex_to<numeric>(c2)));
1043 bool mul::can_make_flat(const expair & p) const
1045 GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
1047 // (x*y)^c == x^c*y^c if c ∈ ℤ
1048 return p.coeff.info(info_flags::integer);
1051 bool mul::can_be_further_expanded(const ex & e)
1053 if (is_exactly_a<mul>(e)) {
1054 for (auto & it : ex_to<mul>(e).seq) {
1055 if (is_exactly_a<add>(it.rest) && it.coeff.info(info_flags::posint))
1058 } else if (is_exactly_a<power>(e)) {
1059 if (is_exactly_a<add>(e.op(0)) && e.op(1).info(info_flags::posint))
1065 ex mul::expand(unsigned options) const
1068 // trivial case: expanding the monomial (~ 30% of all calls)
1069 epvector::const_iterator i = seq.begin(), seq_end = seq.end();
1070 while ((i != seq.end()) && is_a<symbol>(i->rest) && i->coeff.info(info_flags::integer))
1073 setflag(status_flags::expanded);
1078 // do not rename indices if the object has no indices at all
1079 if ((!(options & expand_options::expand_rename_idx)) &&
1080 this->info(info_flags::has_indices))
1081 options |= expand_options::expand_rename_idx;
1083 const bool skip_idx_rename = !(options & expand_options::expand_rename_idx);
1085 // First, expand the children
1086 epvector expanded = expandchildren(options);
1087 const epvector & expanded_seq = (expanded.empty() ? seq : expanded);
1089 // Now, look for all the factors that are sums and multiply each one out
1090 // with the next one that is found while collecting the factors which are
1092 ex last_expanded = _ex1;
1095 non_adds.reserve(expanded_seq.size());
1097 for (const auto & cit : expanded_seq) {
1098 if (is_exactly_a<add>(cit.rest) &&
1099 (cit.coeff.is_equal(_ex1))) {
1100 if (is_exactly_a<add>(last_expanded)) {
1102 // Expand a product of two sums, aggressive version.
1103 // Caring for the overall coefficients in separate loops can
1104 // sometimes give a performance gain of up to 15%!
1106 const int sizedifference = ex_to<add>(last_expanded).seq.size()-ex_to<add>(cit.rest).seq.size();
1107 // add2 is for the inner loop and should be the bigger of the two sums
1108 // in the presence of asymptotically good sorting:
1109 const add& add1 = (sizedifference<0 ? ex_to<add>(last_expanded) : ex_to<add>(cit.rest));
1110 const add& add2 = (sizedifference<0 ? ex_to<add>(cit.rest) : ex_to<add>(last_expanded));
1112 distrseq.reserve(add1.seq.size()+add2.seq.size());
1114 // Multiply add2 with the overall coefficient of add1 and append it to distrseq:
1115 if (!add1.overall_coeff.is_zero()) {
1116 if (add1.overall_coeff.is_equal(_ex1))
1117 distrseq.insert(distrseq.end(), add2.seq.begin(), add2.seq.end());
1119 for (const auto & i : add2.seq)
1120 distrseq.push_back(expair(i.rest, ex_to<numeric>(i.coeff).mul_dyn(ex_to<numeric>(add1.overall_coeff))));
1123 // Multiply add1 with the overall coefficient of add2 and append it to distrseq:
1124 if (!add2.overall_coeff.is_zero()) {
1125 if (add2.overall_coeff.is_equal(_ex1))
1126 distrseq.insert(distrseq.end(), add1.seq.begin(), add1.seq.end());
1128 for (const auto & i : add1.seq)
1129 distrseq.push_back(expair(i.rest, ex_to<numeric>(i.coeff).mul_dyn(ex_to<numeric>(add2.overall_coeff))));
1132 // Compute the new overall coefficient and put it together:
1133 ex tmp_accu = dynallocate<add>(distrseq, add1.overall_coeff*add2.overall_coeff);
1135 exvector add1_dummy_indices, add2_dummy_indices, add_indices;
1138 if (!skip_idx_rename) {
1139 for (const auto & i : add1.seq) {
1140 add_indices = get_all_dummy_indices_safely(i.rest);
1141 add1_dummy_indices.insert(add1_dummy_indices.end(), add_indices.begin(), add_indices.end());
1143 for (const auto & i : add2.seq) {
1144 add_indices = get_all_dummy_indices_safely(i.rest);
1145 add2_dummy_indices.insert(add2_dummy_indices.end(), add_indices.begin(), add_indices.end());
1148 sort(add1_dummy_indices.begin(), add1_dummy_indices.end(), ex_is_less());
1149 sort(add2_dummy_indices.begin(), add2_dummy_indices.end(), ex_is_less());
1150 dummy_subs = rename_dummy_indices_uniquely(add1_dummy_indices, add2_dummy_indices);
1153 // Multiply explicitly all non-numeric terms of add1 and add2:
1154 for (const auto & i2 : add2.seq) {
1155 // We really have to combine terms here in order to compactify
1156 // the result. Otherwise it would become waayy tooo bigg.
1157 numeric oc(*_num0_p);
1159 distrseq2.reserve(add1.seq.size());
1160 const ex i2_new = (skip_idx_rename || (dummy_subs.op(0).nops() == 0) ?
1162 i2.rest.subs(ex_to<lst>(dummy_subs.op(0)),
1163 ex_to<lst>(dummy_subs.op(1)), subs_options::no_pattern));
1164 for (const auto & i1 : add1.seq) {
1165 // Don't push_back expairs which might have a rest that evaluates to a numeric,
1166 // since that would violate an invariant of expairseq:
1167 const ex rest = dynallocate<mul>(i1.rest, i2_new);
1168 if (is_exactly_a<numeric>(rest)) {
1169 oc += ex_to<numeric>(rest).mul(ex_to<numeric>(i1.coeff).mul(ex_to<numeric>(i2.coeff)));
1171 distrseq2.push_back(expair(rest, ex_to<numeric>(i1.coeff).mul_dyn(ex_to<numeric>(i2.coeff))));
1174 tmp_accu += dynallocate<add>(std::move(distrseq2), oc);
1176 last_expanded = tmp_accu;
1178 if (!last_expanded.is_equal(_ex1))
1179 non_adds.push_back(split_ex_to_pair(last_expanded));
1180 last_expanded = cit.rest;
1184 non_adds.push_back(cit);
1188 // Now the only remaining thing to do is to multiply the factors which
1189 // were not sums into the "last_expanded" sum
1190 if (is_exactly_a<add>(last_expanded)) {
1191 size_t n = last_expanded.nops();
1193 distrseq.reserve(n);
1195 if (! skip_idx_rename) {
1196 va = get_all_dummy_indices_safely(mul(non_adds));
1197 sort(va.begin(), va.end(), ex_is_less());
1200 for (size_t i=0; i<n; ++i) {
1201 epvector factors = non_adds;
1202 if (skip_idx_rename)
1203 factors.push_back(split_ex_to_pair(last_expanded.op(i)));
1205 factors.push_back(split_ex_to_pair(rename_dummy_indices_uniquely(va, last_expanded.op(i))));
1206 ex term = dynallocate<mul>(factors, overall_coeff);
1207 if (can_be_further_expanded(term)) {
1208 distrseq.push_back(term.expand());
1211 ex_to<basic>(term).setflag(status_flags::expanded);
1212 distrseq.push_back(term);
1216 return dynallocate<add>(distrseq).setflag(options == 0 ? status_flags::expanded : 0);
1219 non_adds.push_back(split_ex_to_pair(last_expanded));
1220 ex result = dynallocate<mul>(non_adds, overall_coeff);
1221 if (can_be_further_expanded(result)) {
1222 return result.expand();
1225 ex_to<basic>(result).setflag(status_flags::expanded);
1232 // new virtual functions which can be overridden by derived classes
1238 // non-virtual functions in this class
1242 /** Member-wise expand the expairs representing this sequence. This must be
1243 * overridden from expairseq::expandchildren() and done iteratively in order
1244 * to allow for early cancellations and thus safe memory.
1246 * @see mul::expand()
1247 * @return epvector containing expanded pairs, empty if no members
1248 * had to be changed. */
1249 epvector mul::expandchildren(unsigned options) const
1251 auto cit = seq.begin(), last = seq.end();
1253 const ex & factor = recombine_pair_to_ex(*cit);
1254 const ex & expanded_factor = factor.expand(options);
1255 if (!are_ex_trivially_equal(factor,expanded_factor)) {
1257 // something changed, copy seq, eval and return it
1259 s.reserve(seq.size());
1261 // copy parts of seq which are known not to have changed
1262 auto cit2 = seq.begin();
1268 // copy first changed element
1269 s.push_back(split_ex_to_pair(expanded_factor));
1273 while (cit2!=last) {
1274 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*cit2).expand(options)));
1282 return epvector(); // nothing has changed
1285 GINAC_BIND_UNARCHIVER(mul);
1287 } // namespace GiNaC