3 * Implementation of class for extended truncated power series and
4 * methods for series expansion. */
7 * GiNaC Copyright (C) 1999-2019 Johannes Gutenberg University Mainz, Germany
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 #include "inifcns.h" // for Order function
30 #include "relational.h"
31 #include "operators.h"
43 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(pseries, basic,
44 print_func<print_context>(&pseries::do_print).
45 print_func<print_latex>(&pseries::do_print_latex).
46 print_func<print_tree>(&pseries::do_print_tree).
47 print_func<print_python>(&pseries::do_print_python).
48 print_func<print_python_repr>(&pseries::do_print_python_repr))
55 pseries::pseries() { }
62 /** Construct pseries from a vector of coefficients and powers.
63 * expair.rest holds the coefficient, expair.coeff holds the power.
64 * The powers must be integers (positive or negative) and in ascending order;
65 * the last coefficient can be Order(_ex1) to represent a truncated,
66 * non-terminating series.
68 * @param rel_ expansion variable and point (must hold a relational)
69 * @param ops_ vector of {coefficient, power} pairs (coefficient must not be zero)
70 * @return newly constructed pseries */
71 pseries::pseries(const ex &rel_, const epvector &ops_)
74 #ifdef DO_GINAC_ASSERT
76 while (i != seq.end()) {
79 GINAC_ASSERT(!is_order_function(i->rest));
82 GINAC_ASSERT(is_a<numeric>(i->coeff));
83 GINAC_ASSERT(ex_to<numeric>(i->coeff) < ex_to<numeric>(ip1->coeff));
86 #endif // def DO_GINAC_ASSERT
87 GINAC_ASSERT(is_a<relational>(rel_));
88 GINAC_ASSERT(is_a<symbol>(rel_.lhs()));
92 pseries::pseries(const ex &rel_, epvector &&ops_)
93 : seq(std::move(ops_))
95 #ifdef DO_GINAC_ASSERT
97 while (i != seq.end()) {
100 GINAC_ASSERT(!is_order_function(i->rest));
103 GINAC_ASSERT(is_a<numeric>(i->coeff));
104 GINAC_ASSERT(ex_to<numeric>(i->coeff) < ex_to<numeric>(ip1->coeff));
107 #endif // def DO_GINAC_ASSERT
108 GINAC_ASSERT(is_a<relational>(rel_));
109 GINAC_ASSERT(is_a<symbol>(rel_.lhs()));
119 void pseries::read_archive(const archive_node &n, lst &sym_lst)
121 inherited::read_archive(n, sym_lst);
122 auto first = n.find_first("coeff");
123 auto last = n.find_last("power");
125 seq.reserve((last-first)/2);
127 for (auto loc = first; loc < last;) {
130 n.find_ex_by_loc(loc++, rest, sym_lst);
131 n.find_ex_by_loc(loc++, coeff, sym_lst);
132 seq.push_back(expair(rest, coeff));
135 n.find_ex("var", var, sym_lst);
136 n.find_ex("point", point, sym_lst);
139 void pseries::archive(archive_node &n) const
141 inherited::archive(n);
142 for (auto & it : seq) {
143 n.add_ex("coeff", it.rest);
144 n.add_ex("power", it.coeff);
146 n.add_ex("var", var);
147 n.add_ex("point", point);
152 // functions overriding virtual functions from base classes
155 void pseries::print_series(const print_context & c, const char *openbrace, const char *closebrace, const char *mul_sym, const char *pow_sym, unsigned level) const
157 if (precedence() <= level)
160 // objects of type pseries must not have any zero entries, so the
161 // trivial (zero) pseries needs a special treatment here:
165 auto i = seq.begin(), end = seq.end();
168 // print a sign, if needed
169 if (i != seq.begin())
172 if (!is_order_function(i->rest)) {
174 // print 'rest', i.e. the expansion coefficient
175 if (i->rest.info(info_flags::numeric) &&
176 i->rest.info(info_flags::positive)) {
179 c.s << openbrace << '(';
181 c.s << ')' << closebrace;
184 // print 'coeff', something like (x-1)^42
185 if (!i->coeff.is_zero()) {
187 if (!point.is_zero()) {
188 c.s << openbrace << '(';
189 (var-point).print(c);
190 c.s << ')' << closebrace;
193 if (i->coeff.compare(_ex1)) {
196 if (i->coeff.info(info_flags::negative)) {
206 Order(pow(var - point, i->coeff)).print(c);
210 if (precedence() <= level)
214 void pseries::do_print(const print_context & c, unsigned level) const
216 print_series(c, "", "", "*", "^", level);
219 void pseries::do_print_latex(const print_latex & c, unsigned level) const
221 print_series(c, "{", "}", " ", "^", level);
224 void pseries::do_print_python(const print_python & c, unsigned level) const
226 print_series(c, "", "", "*", "**", level);
229 void pseries::do_print_tree(const print_tree & c, unsigned level) const
231 c.s << std::string(level, ' ') << class_name() << " @" << this
232 << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
234 size_t num = seq.size();
235 for (size_t i=0; i<num; ++i) {
236 seq[i].rest.print(c, level + c.delta_indent);
237 seq[i].coeff.print(c, level + c.delta_indent);
238 c.s << std::string(level + c.delta_indent, ' ') << "-----" << std::endl;
240 var.print(c, level + c.delta_indent);
241 point.print(c, level + c.delta_indent);
244 void pseries::do_print_python_repr(const print_python_repr & c, unsigned level) const
246 c.s << class_name() << "(relational(";
251 size_t num = seq.size();
252 for (size_t i=0; i<num; ++i) {
256 seq[i].rest.print(c);
258 seq[i].coeff.print(c);
264 int pseries::compare_same_type(const basic & other) const
266 GINAC_ASSERT(is_a<pseries>(other));
267 const pseries &o = static_cast<const pseries &>(other);
269 // first compare the lengths of the series...
270 if (seq.size()>o.seq.size())
272 if (seq.size()<o.seq.size())
275 // ...then the expansion point...
276 int cmpval = var.compare(o.var);
279 cmpval = point.compare(o.point);
283 // ...and if that failed the individual elements
284 auto it = seq.begin(), o_it = o.seq.begin();
285 while (it!=seq.end() && o_it!=o.seq.end()) {
286 cmpval = it->compare(*o_it);
293 // so they are equal.
297 /** Return the number of operands including a possible order term. */
298 size_t pseries::nops() const
303 /** Return the ith term in the series when represented as a sum. */
304 ex pseries::op(size_t i) const
307 throw (std::out_of_range("op() out of range"));
309 if (is_order_function(seq[i].rest))
310 return Order(pow(var-point, seq[i].coeff));
311 return seq[i].rest * pow(var - point, seq[i].coeff);
314 /** Return degree of highest power of the series. This is usually the exponent
315 * of the Order term. If s is not the expansion variable of the series, the
316 * series is examined termwise. */
317 int pseries::degree(const ex &s) const
323 // Return last/greatest exponent
324 return ex_to<numeric>((seq.end()-1)->coeff).to_int();
326 int max_pow = std::numeric_limits<int>::min();
327 for (auto & it : seq)
328 max_pow = std::max(max_pow, it.rest.degree(s));
332 /** Return degree of lowest power of the series. This is usually the exponent
333 * of the leading term. If s is not the expansion variable of the series, the
334 * series is examined termwise. If s is the expansion variable but the
335 * expansion point is not zero the series is not expanded to find the degree.
336 * I.e.: (1-x) + (1-x)^2 + Order((1-x)^3) has ldegree(x) 1, not 0. */
337 int pseries::ldegree(const ex &s) const
343 // Return first/smallest exponent
344 return ex_to<numeric>((seq.begin())->coeff).to_int();
346 int min_pow = std::numeric_limits<int>::max();
347 for (auto & it : seq)
348 min_pow = std::min(min_pow, it.rest.degree(s));
352 /** Return coefficient of degree n in power series if s is the expansion
353 * variable. If the expansion point is nonzero, by definition the n=1
354 * coefficient in s of a+b*(s-z)+c*(s-z)^2+Order((s-z)^3) is b (assuming
355 * the expansion took place in the s in the first place).
356 * If s is not the expansion variable, an attempt is made to convert the
357 * series to a polynomial and return the corresponding coefficient from
359 ex pseries::coeff(const ex &s, int n) const
361 if (var.is_equal(s)) {
365 // Binary search in sequence for given power
366 numeric looking_for = numeric(n);
367 int lo = 0, hi = seq.size() - 1;
369 int mid = (lo + hi) / 2;
370 GINAC_ASSERT(is_exactly_a<numeric>(seq[mid].coeff));
371 int cmp = ex_to<numeric>(seq[mid].coeff).compare(looking_for);
377 return seq[mid].rest;
382 throw(std::logic_error("pseries::coeff: compare() didn't return -1, 0 or 1"));
387 return convert_to_poly().coeff(s, n);
391 ex pseries::collect(const ex &s, bool distributed) const
396 /** Perform coefficient-wise automatic term rewriting rules in this class. */
397 ex pseries::eval() const
399 if (flags & status_flags::evaluated) {
403 // Construct a new series with evaluated coefficients
405 new_seq.reserve(seq.size());
406 for (auto & it : seq)
407 new_seq.push_back(expair(it.rest, it.coeff));
409 return dynallocate<pseries>(relational(var,point), std::move(new_seq)).setflag(status_flags::evaluated);
412 /** Evaluate coefficients numerically. */
413 ex pseries::evalf() const
415 // Construct a new series with evaluated coefficients
417 new_seq.reserve(seq.size());
418 for (auto & it : seq)
419 new_seq.push_back(expair(it.rest, it.coeff));
421 return dynallocate<pseries>(relational(var,point), std::move(new_seq)).setflag(status_flags::evaluated);
424 ex pseries::conjugate() const
426 if(!var.info(info_flags::real))
427 return conjugate_function(*this).hold();
429 std::unique_ptr<epvector> newseq(conjugateepvector(seq));
430 ex newpoint = point.conjugate();
432 if (!newseq && are_ex_trivially_equal(point, newpoint)) {
436 return dynallocate<pseries>(var==newpoint, newseq ? std::move(*newseq) : seq);
439 ex pseries::real_part() const
441 if(!var.info(info_flags::real))
442 return real_part_function(*this).hold();
443 ex newpoint = point.real_part();
444 if(newpoint != point)
445 return real_part_function(*this).hold();
448 v.reserve(seq.size());
449 for (auto & it : seq)
450 v.push_back(expair((it.rest).real_part(), it.coeff));
451 return dynallocate<pseries>(var==point, std::move(v));
454 ex pseries::imag_part() const
456 if(!var.info(info_flags::real))
457 return imag_part_function(*this).hold();
458 ex newpoint = point.real_part();
459 if(newpoint != point)
460 return imag_part_function(*this).hold();
463 v.reserve(seq.size());
464 for (auto & it : seq)
465 v.push_back(expair((it.rest).imag_part(), it.coeff));
466 return dynallocate<pseries>(var==point, std::move(v));
469 ex pseries::eval_integ() const
471 std::unique_ptr<epvector> newseq(nullptr);
472 for (auto i=seq.begin(); i!=seq.end(); ++i) {
474 newseq->push_back(expair(i->rest.eval_integ(), i->coeff));
477 ex newterm = i->rest.eval_integ();
478 if (!are_ex_trivially_equal(newterm, i->rest)) {
479 newseq.reset(new epvector);
480 newseq->reserve(seq.size());
481 for (auto j=seq.begin(); j!=i; ++j)
482 newseq->push_back(*j);
483 newseq->push_back(expair(newterm, i->coeff));
487 ex newpoint = point.eval_integ();
488 if (newseq || !are_ex_trivially_equal(newpoint, point))
489 return dynallocate<pseries>(var==newpoint, std::move(*newseq));
493 ex pseries::evalm() const
495 // evalm each coefficient
497 bool something_changed = false;
498 for (auto i=seq.begin(); i!=seq.end(); ++i) {
499 if (something_changed) {
500 ex newcoeff = i->rest.evalm();
501 if (!newcoeff.is_zero())
502 newseq.push_back(expair(newcoeff, i->coeff));
504 ex newcoeff = i->rest.evalm();
505 if (!are_ex_trivially_equal(newcoeff, i->rest)) {
506 something_changed = true;
507 newseq.reserve(seq.size());
508 std::copy(seq.begin(), i, std::back_inserter<epvector>(newseq));
509 if (!newcoeff.is_zero())
510 newseq.push_back(expair(newcoeff, i->coeff));
514 if (something_changed)
515 return dynallocate<pseries>(var==point, std::move(newseq));
520 ex pseries::subs(const exmap & m, unsigned options) const
522 // If expansion variable is being substituted, convert the series to a
523 // polynomial and do the substitution there because the result might
524 // no longer be a power series
525 if (m.find(var) != m.end())
526 return convert_to_poly(true).subs(m, options);
528 // Otherwise construct a new series with substituted coefficients and
531 newseq.reserve(seq.size());
532 for (auto & it : seq)
533 newseq.push_back(expair(it.rest.subs(m, options), it.coeff));
534 return dynallocate<pseries>(relational(var,point.subs(m, options)), std::move(newseq));
537 /** Implementation of ex::expand() for a power series. It expands all the
538 * terms individually and returns the resulting series as a new pseries. */
539 ex pseries::expand(unsigned options) const
542 for (auto & it : seq) {
543 ex restexp = it.rest.expand();
544 if (!restexp.is_zero())
545 newseq.push_back(expair(restexp, it.coeff));
547 return dynallocate<pseries>(relational(var,point), std::move(newseq)).setflag(options == 0 ? status_flags::expanded : 0);
550 /** Implementation of ex::diff() for a power series.
552 ex pseries::derivative(const symbol & s) const
558 // FIXME: coeff might depend on var
559 for (auto & it : seq) {
560 if (is_order_function(it.rest)) {
561 new_seq.push_back(expair(it.rest, it.coeff - 1));
563 ex c = it.rest * it.coeff;
565 new_seq.push_back(expair(c, it.coeff - 1));
571 for (auto & it : seq) {
572 if (is_order_function(it.rest)) {
573 new_seq.push_back(it);
575 ex c = it.rest.diff(s);
577 new_seq.push_back(expair(c, it.coeff));
582 return pseries(relational(var,point), std::move(new_seq));
585 ex pseries::convert_to_poly(bool no_order) const
588 for (auto & it : seq) {
589 if (is_order_function(it.rest)) {
591 e += Order(pow(var - point, it.coeff));
593 e += it.rest * pow(var - point, it.coeff);
598 bool pseries::is_terminating() const
600 return seq.empty() || !is_order_function((seq.end()-1)->rest);
603 ex pseries::coeffop(size_t i) const
606 throw (std::out_of_range("coeffop() out of range"));
610 ex pseries::exponop(size_t i) const
613 throw (std::out_of_range("exponop() out of range"));
619 * Implementations of series expansion
622 /** Default implementation of ex::series(). This performs Taylor expansion.
624 ex basic::series(const relational & r, int order, unsigned options) const
627 const symbol &s = ex_to<symbol>(r.lhs());
629 // default for order-values that make no sense for Taylor expansion
630 if ((order <= 0) && this->has(s)) {
631 seq.push_back(expair(Order(_ex1), order));
632 return pseries(r, std::move(seq));
635 // do Taylor expansion
638 ex coeff = deriv.subs(r, subs_options::no_pattern);
640 if (!coeff.is_zero()) {
641 seq.push_back(expair(coeff, _ex0));
645 for (n=1; n<order; ++n) {
647 // We need to test for zero in order to see if the series terminates.
648 // The problem is that there is no such thing as a perfect test for
649 // zero. Expanding the term occasionally helps a little...
650 deriv = deriv.diff(s).expand();
651 if (deriv.is_zero()) // Series terminates
652 return pseries(r, std::move(seq));
654 coeff = deriv.subs(r, subs_options::no_pattern);
655 if (!coeff.is_zero())
656 seq.push_back(expair(fac * coeff, n));
659 // Higher-order terms, if present
660 deriv = deriv.diff(s);
661 if (!deriv.expand().is_zero())
662 seq.push_back(expair(Order(_ex1), n));
663 return pseries(r, std::move(seq));
667 /** Implementation of ex::series() for symbols.
669 ex symbol::series(const relational & r, int order, unsigned options) const
672 const ex point = r.rhs();
673 GINAC_ASSERT(is_a<symbol>(r.lhs()));
675 if (this->is_equal_same_type(ex_to<symbol>(r.lhs()))) {
676 if (order > 0 && !point.is_zero())
677 seq.push_back(expair(point, _ex0));
679 seq.push_back(expair(_ex1, _ex1));
681 seq.push_back(expair(Order(_ex1), numeric(order)));
683 seq.push_back(expair(*this, _ex0));
684 return pseries(r, std::move(seq));
688 /** Add one series object to another, producing a pseries object that
689 * represents the sum.
691 * @param other pseries object to add with
692 * @return the sum as a pseries */
693 ex pseries::add_series(const pseries &other) const
695 // Adding two series with different variables or expansion points
696 // results in an empty (constant) series
697 if (!is_compatible_to(other)) {
698 epvector nul { expair(Order(_ex1), _ex0) };
699 return pseries(relational(var,point), std::move(nul));
704 auto a = seq.begin(), a_end = seq.end();
705 auto b = other.seq.begin(), b_end = other.seq.end();
706 int pow_a = std::numeric_limits<int>::max(), pow_b = std::numeric_limits<int>::max();
708 // If a is empty, fill up with elements from b and stop
711 new_seq.push_back(*b);
716 pow_a = ex_to<numeric>((*a).coeff).to_int();
718 // If b is empty, fill up with elements from a and stop
721 new_seq.push_back(*a);
726 pow_b = ex_to<numeric>((*b).coeff).to_int();
728 // a and b are non-empty, compare powers
730 // a has lesser power, get coefficient from a
731 new_seq.push_back(*a);
732 if (is_order_function((*a).rest))
735 } else if (pow_b < pow_a) {
736 // b has lesser power, get coefficient from b
737 new_seq.push_back(*b);
738 if (is_order_function((*b).rest))
742 // Add coefficient of a and b
743 if (is_order_function((*a).rest) || is_order_function((*b).rest)) {
744 new_seq.push_back(expair(Order(_ex1), (*a).coeff));
745 break; // Order term ends the sequence
747 ex sum = (*a).rest + (*b).rest;
748 if (!(sum.is_zero()))
749 new_seq.push_back(expair(sum, numeric(pow_a)));
755 return pseries(relational(var,point), std::move(new_seq));
759 /** Implementation of ex::series() for sums. This performs series addition when
760 * adding pseries objects.
762 ex add::series(const relational & r, int order, unsigned options) const
764 ex acc; // Series accumulator
766 // Get first term from overall_coeff
767 acc = overall_coeff.series(r, order, options);
769 // Add remaining terms
770 for (auto & it : seq) {
772 if (is_exactly_a<pseries>(it.rest))
775 op = it.rest.series(r, order, options);
776 if (!it.coeff.is_equal(_ex1))
777 op = ex_to<pseries>(op).mul_const(ex_to<numeric>(it.coeff));
780 acc = ex_to<pseries>(acc).add_series(ex_to<pseries>(op));
786 /** Multiply a pseries object with a numeric constant, producing a pseries
787 * object that represents the product.
789 * @param other constant to multiply with
790 * @return the product as a pseries */
791 ex pseries::mul_const(const numeric &other) const
794 new_seq.reserve(seq.size());
796 for (auto & it : seq) {
797 if (!is_order_function(it.rest))
798 new_seq.push_back(expair(it.rest * other, it.coeff));
800 new_seq.push_back(it);
802 return pseries(relational(var,point), std::move(new_seq));
806 /** Multiply one pseries object to another, producing a pseries object that
807 * represents the product.
809 * @param other pseries object to multiply with
810 * @return the product as a pseries */
811 ex pseries::mul_series(const pseries &other) const
813 // Multiplying two series with different variables or expansion points
814 // results in an empty (constant) series
815 if (!is_compatible_to(other)) {
816 epvector nul { expair(Order(_ex1), _ex0) };
817 return pseries(relational(var,point), std::move(nul));
820 if (seq.empty() || other.seq.empty()) {
821 return dynallocate<pseries>(var==point, epvector());
824 // Series multiplication
826 const int a_max = degree(var);
827 const int b_max = other.degree(var);
828 const int a_min = ldegree(var);
829 const int b_min = other.ldegree(var);
830 const int cdeg_min = a_min + b_min;
831 int cdeg_max = a_max + b_max;
833 int higher_order_a = std::numeric_limits<int>::max();
834 int higher_order_b = std::numeric_limits<int>::max();
835 if (is_order_function(coeff(var, a_max)))
836 higher_order_a = a_max + b_min;
837 if (is_order_function(other.coeff(var, b_max)))
838 higher_order_b = b_max + a_min;
839 const int higher_order_c = std::min(higher_order_a, higher_order_b);
840 if (cdeg_max >= higher_order_c)
841 cdeg_max = higher_order_c - 1;
843 std::map<int, ex> rest_map_a, rest_map_b;
844 for (const auto& it : seq)
845 rest_map_a[ex_to<numeric>(it.coeff).to_int()] = it.rest;
847 if (other.var.is_equal(var))
848 for (const auto& it : other.seq)
849 rest_map_b[ex_to<numeric>(it.coeff).to_int()] = it.rest;
851 for (int cdeg=cdeg_min; cdeg<=cdeg_max; ++cdeg) {
853 // c(i)=a(0)b(i)+...+a(i)b(0)
854 for (int i=a_min; cdeg-i>=b_min; ++i) {
855 const auto& ita = rest_map_a.find(i);
856 if (ita == rest_map_a.end())
858 const auto& itb = rest_map_b.find(cdeg-i);
859 if (itb == rest_map_b.end())
861 if (!is_order_function(ita->second) && !is_order_function(itb->second))
862 co += ita->second * itb->second;
865 new_seq.push_back(expair(co, numeric(cdeg)));
867 if (higher_order_c < std::numeric_limits<int>::max())
868 new_seq.push_back(expair(Order(_ex1), numeric(higher_order_c)));
869 return pseries(relational(var, point), std::move(new_seq));
873 /** Implementation of ex::series() for product. This performs series
874 * multiplication when multiplying series.
876 ex mul::series(const relational & r, int order, unsigned options) const
878 pseries acc; // Series accumulator
880 GINAC_ASSERT(is_a<symbol>(r.lhs()));
881 const ex& sym = r.lhs();
883 // holds ldegrees of the series of individual factors
884 std::vector<int> ldegrees;
885 std::vector<bool> ldegree_redo;
887 // find minimal degrees
888 // first round: obtain a bound up to which minimal degrees have to be
890 for (auto & it : seq) {
895 if (expon.info(info_flags::integer)) {
897 factor = ex_to<numeric>(expon).to_int();
899 buf = recombine_pair_to_ex(it);
902 int real_ldegree = 0;
903 bool flag_redo = false;
905 real_ldegree = buf.expand().ldegree(sym-r.rhs());
906 } catch (std::runtime_error) {}
908 if (real_ldegree == 0) {
910 // This case must terminate, otherwise we would have division by
915 real_ldegree = buf.series(r, orderloop, options).ldegree(sym);
916 } while (real_ldegree == orderloop);
918 // Here it is possible that buf does not have a ldegree, therefore
919 // check only if ldegree is negative, otherwise reconsider the case
920 // in the second round.
921 real_ldegree = buf.series(r, 0, options).ldegree(sym);
922 if (real_ldegree == 0)
927 ldegrees.push_back(factor * real_ldegree);
928 ldegree_redo.push_back(flag_redo);
931 int degbound = order-std::accumulate(ldegrees.begin(), ldegrees.end(), 0);
932 // Second round: determine the remaining positive ldegrees by the series
934 // here we can ignore ldegrees larger than degbound
936 for (auto & it : seq) {
937 if ( ldegree_redo[j] ) {
941 if (expon.info(info_flags::integer)) {
943 factor = ex_to<numeric>(expon).to_int();
945 buf = recombine_pair_to_ex(it);
947 int real_ldegree = 0;
951 real_ldegree = buf.series(r, orderloop, options).ldegree(sym);
952 } while ((real_ldegree == orderloop)
953 && (factor*real_ldegree < degbound));
954 ldegrees[j] = factor * real_ldegree;
955 degbound -= factor * real_ldegree;
960 int degsum = std::accumulate(ldegrees.begin(), ldegrees.end(), 0);
962 if (degsum >= order) {
963 epvector epv { expair(Order(_ex1), order) };
964 return dynallocate<pseries>(r, std::move(epv));
967 // Multiply with remaining terms
968 auto itd = ldegrees.begin();
969 for (auto it=seq.begin(), itend=seq.end(); it!=itend; ++it, ++itd) {
971 // do series expansion with adjusted order
972 ex op = recombine_pair_to_ex(*it).series(r, order-degsum+(*itd), options);
974 // Series multiplication
975 if (it == seq.begin())
976 acc = ex_to<pseries>(op);
978 acc = ex_to<pseries>(acc.mul_series(ex_to<pseries>(op)));
981 return acc.mul_const(ex_to<numeric>(overall_coeff));
985 /** Compute the p-th power of a series.
987 * @param p power to compute
988 * @param deg truncation order of series calculation */
989 ex pseries::power_const(const numeric &p, int deg) const
992 // (due to Leonhard Euler)
993 // let A(x) be this series and for the time being let it start with a
994 // constant (later we'll generalize):
995 // A(x) = a_0 + a_1*x + a_2*x^2 + ...
996 // We want to compute
998 // C(x) = c_0 + c_1*x + c_2*x^2 + ...
999 // Taking the derivative on both sides and multiplying with A(x) one
1000 // immediately arrives at
1001 // C'(x)*A(x) = p*C(x)*A'(x)
1002 // Multiplying this out and comparing coefficients we get the recurrence
1004 // c_i = (i*p*a_i*c_0 + ((i-1)*p-1)*a_{i-1}*c_1 + ...
1005 // ... + (p-(i-1))*a_1*c_{i-1})/(a_0*i)
1006 // which can easily be solved given the starting value c_0 = (a_0)^p.
1007 // For the more general case where the leading coefficient of A(x) is not
1008 // a constant, just consider A2(x) = A(x)*x^m, with some integer m and
1009 // repeat the above derivation. The leading power of C2(x) = A2(x)^2 is
1010 // then of course x^(p*m) but the recurrence formula still holds.
1013 // as a special case, handle the empty (zero) series honoring the
1014 // usual power laws such as implemented in power::eval()
1015 if (p.real().is_zero())
1016 throw std::domain_error("pseries::power_const(): pow(0,I) is undefined");
1017 else if (p.real().is_negative())
1018 throw pole_error("pseries::power_const(): division by zero",1);
1023 const int ldeg = ldegree(var);
1024 if (!(p*ldeg).is_integer())
1025 throw std::runtime_error("pseries::power_const(): trying to assemble a Puiseux series");
1027 // adjust number of coefficients
1028 int numcoeff = deg - (p*ldeg).to_int();
1029 if (numcoeff <= 0) {
1030 epvector epv { expair(Order(_ex1), deg) };
1031 return dynallocate<pseries>(relational(var,point), std::move(epv));
1034 // O(x^n)^(-m) is undefined
1035 if (seq.size() == 1 && is_order_function(seq[0].rest) && p.real().is_negative())
1036 throw pole_error("pseries::power_const(): division by zero",1);
1038 // Compute coefficients of the powered series
1040 co.reserve(numcoeff);
1041 co.push_back(pow(coeff(var, ldeg), p));
1042 for (int i=1; i<numcoeff; ++i) {
1044 for (int j=1; j<=i; ++j) {
1045 ex c = coeff(var, j + ldeg);
1046 if (is_order_function(c)) {
1047 co.push_back(Order(_ex1));
1050 sum += (p * j - (i - j)) * co[i - j] * c;
1052 co.push_back(sum / coeff(var, ldeg) / i);
1055 // Construct new series (of non-zero coefficients)
1057 bool higher_order = false;
1058 for (int i=0; i<numcoeff; ++i) {
1059 if (!co[i].is_zero())
1060 new_seq.push_back(expair(co[i], p * ldeg + i));
1061 if (is_order_function(co[i])) {
1062 higher_order = true;
1067 new_seq.push_back(expair(Order(_ex1), p * ldeg + numcoeff));
1069 return pseries(relational(var,point), std::move(new_seq));
1073 /** Return a new pseries object with the powers shifted by deg. */
1074 pseries pseries::shift_exponents(int deg) const
1076 epvector newseq = seq;
1077 for (auto & it : newseq)
1079 return pseries(relational(var, point), std::move(newseq));
1083 /** Implementation of ex::series() for powers. This performs Laurent expansion
1084 * of reciprocals of series at singularities.
1085 * @see ex::series */
1086 ex power::series(const relational & r, int order, unsigned options) const
1088 // If basis is already a series, just power it
1089 if (is_exactly_a<pseries>(basis))
1090 return ex_to<pseries>(basis).power_const(ex_to<numeric>(exponent), order);
1092 // Basis is not a series, may there be a singularity?
1093 bool must_expand_basis = false;
1095 basis.subs(r, subs_options::no_pattern);
1096 } catch (pole_error) {
1097 must_expand_basis = true;
1100 bool exponent_is_regular = true;
1102 exponent.subs(r, subs_options::no_pattern);
1103 } catch (pole_error) {
1104 exponent_is_regular = false;
1107 if (!exponent_is_regular) {
1108 ex l = exponent*log(basis);
1110 ex le = l.series(r, order, options);
1111 // Note: expanding exp(l) won't help, since that will attempt
1112 // Taylor expansion, and fail (because exponent is "singular")
1113 // Still l itself might be expanded in Taylor series.
1115 // sin(x)/x*log(cos(x))
1117 return exp(le).series(r, order, options);
1118 // Note: if l happens to have a Laurent expansion (with
1119 // negative powers of (var - point)), expanding exp(le)
1120 // will barf (which is The Right Thing).
1123 // Is the expression of type something^(-int)?
1124 if (!must_expand_basis && !exponent.info(info_flags::negint)
1125 && (!is_a<add>(basis) || !is_a<numeric>(exponent)))
1126 return basic::series(r, order, options);
1128 // Is the expression of type 0^something?
1129 if (!must_expand_basis && !basis.subs(r, subs_options::no_pattern).is_zero()
1130 && (!is_a<add>(basis) || !is_a<numeric>(exponent)))
1131 return basic::series(r, order, options);
1133 // Singularity encountered, is the basis equal to (var - point)?
1134 if (basis.is_equal(r.lhs() - r.rhs())) {
1136 if (ex_to<numeric>(exponent).to_int() < order)
1137 new_seq.push_back(expair(_ex1, exponent));
1139 new_seq.push_back(expair(Order(_ex1), exponent));
1140 return pseries(r, std::move(new_seq));
1143 // No, expand basis into series
1146 if (is_a<numeric>(exponent)) {
1147 numexp = ex_to<numeric>(exponent);
1151 const ex& sym = r.lhs();
1152 // find existing minimal degree
1153 ex eb = basis.expand();
1154 int real_ldegree = 0;
1155 if (eb.info(info_flags::rational_function))
1156 real_ldegree = eb.ldegree(sym-r.rhs());
1157 if (real_ldegree == 0) {
1161 real_ldegree = basis.series(r, orderloop, options).ldegree(sym);
1162 } while (real_ldegree == orderloop);
1165 if (!(real_ldegree*numexp).is_integer())
1166 throw std::runtime_error("pseries::power_const(): trying to assemble a Puiseux series");
1167 ex e = basis.series(r, (order + real_ldegree*(1-numexp)).to_int(), options);
1171 result = ex_to<pseries>(e).power_const(numexp, order);
1172 } catch (pole_error) {
1173 epvector ser { expair(Order(_ex1), order) };
1174 result = pseries(r, std::move(ser));
1181 /** Re-expansion of a pseries object. */
1182 ex pseries::series(const relational & r, int order, unsigned options) const
1184 const ex p = r.rhs();
1185 GINAC_ASSERT(is_a<symbol>(r.lhs()));
1186 const symbol &s = ex_to<symbol>(r.lhs());
1188 if (var.is_equal(s) && point.is_equal(p)) {
1189 if (order > degree(s))
1193 for (auto & it : seq) {
1194 int o = ex_to<numeric>(it.coeff).to_int();
1196 new_seq.push_back(expair(Order(_ex1), o));
1199 new_seq.push_back(it);
1201 return pseries(r, std::move(new_seq));
1204 return convert_to_poly().series(r, order, options);
1207 ex integral::series(const relational & r, int order, unsigned options) const
1210 throw std::logic_error("Cannot series expand wrt dummy variable");
1212 // Expanding integrand with r substituted taken in boundaries.
1213 ex fseries = f.series(r, order, options);
1214 epvector fexpansion;
1215 fexpansion.reserve(fseries.nops());
1216 for (size_t i=0; i<fseries.nops(); ++i) {
1217 ex currcoeff = ex_to<pseries>(fseries).coeffop(i);
1218 currcoeff = (currcoeff == Order(_ex1))
1220 : integral(x, a.subs(r), b.subs(r), currcoeff);
1222 fexpansion.push_back(
1223 expair(currcoeff, ex_to<pseries>(fseries).exponop(i)));
1226 // Expanding lower boundary
1227 ex result = dynallocate<pseries>(r, std::move(fexpansion));
1228 ex aseries = (a-a.subs(r)).series(r, order, options);
1229 fseries = f.series(x == (a.subs(r)), order, options);
1230 for (size_t i=0; i<fseries.nops(); ++i) {
1231 ex currcoeff = ex_to<pseries>(fseries).coeffop(i);
1232 if (is_order_function(currcoeff))
1234 ex currexpon = ex_to<pseries>(fseries).exponop(i);
1235 int orderforf = order-ex_to<numeric>(currexpon).to_int()-1;
1236 currcoeff = currcoeff.series(r, orderforf);
1237 ex term = ex_to<pseries>(aseries).power_const(ex_to<numeric>(currexpon+1),order);
1238 term = ex_to<pseries>(term).mul_const(ex_to<numeric>(-1/(currexpon+1)));
1239 term = ex_to<pseries>(term).mul_series(ex_to<pseries>(currcoeff));
1240 result = ex_to<pseries>(result).add_series(ex_to<pseries>(term));
1243 // Expanding upper boundary
1244 ex bseries = (b-b.subs(r)).series(r, order, options);
1245 fseries = f.series(x == (b.subs(r)), order, options);
1246 for (size_t i=0; i<fseries.nops(); ++i) {
1247 ex currcoeff = ex_to<pseries>(fseries).coeffop(i);
1248 if (is_order_function(currcoeff))
1250 ex currexpon = ex_to<pseries>(fseries).exponop(i);
1251 int orderforf = order-ex_to<numeric>(currexpon).to_int()-1;
1252 currcoeff = currcoeff.series(r, orderforf);
1253 ex term = ex_to<pseries>(bseries).power_const(ex_to<numeric>(currexpon+1),order);
1254 term = ex_to<pseries>(term).mul_const(ex_to<numeric>(1/(currexpon+1)));
1255 term = ex_to<pseries>(term).mul_series(ex_to<pseries>(currcoeff));
1256 result = ex_to<pseries>(result).add_series(ex_to<pseries>(term));
1263 /** Compute the truncated series expansion of an expression.
1264 * This function returns an expression containing an object of class pseries
1265 * to represent the series. If the series does not terminate within the given
1266 * truncation order, the last term of the series will be an order term.
1268 * @param r expansion relation, lhs holds variable and rhs holds point
1269 * @param order truncation order of series calculations
1270 * @param options of class series_options
1271 * @return an expression holding a pseries object */
1272 ex ex::series(const ex & r, int order, unsigned options) const
1277 if (is_a<relational>(r))
1278 rel_ = ex_to<relational>(r);
1279 else if (is_a<symbol>(r))
1280 rel_ = relational(r,_ex0);
1282 throw (std::logic_error("ex::series(): expansion point has unknown type"));
1284 e = bp->series(rel_, order, options);
1288 GINAC_BIND_UNARCHIVER(pseries);
1290 } // namespace GiNaC