3 * Implementation of class for extended truncated power series and
4 * methods for series expansion. */
7 * GiNaC Copyright (C) 1999-2015 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 GINAC_ASSERT(is_a<relational>(rel_));
75 GINAC_ASSERT(is_a<symbol>(rel_.lhs()));
79 pseries::pseries(const ex &rel_, epvector &&ops_)
80 : seq(std::move(ops_))
82 GINAC_ASSERT(is_a<relational>(rel_));
83 GINAC_ASSERT(is_a<symbol>(rel_.lhs()));
93 void pseries::read_archive(const archive_node &n, lst &sym_lst)
95 inherited::read_archive(n, sym_lst);
96 auto first = n.find_first("coeff");
97 auto last = n.find_last("power");
99 seq.reserve((last-first)/2);
101 for (auto loc = first; loc < last;) {
104 n.find_ex_by_loc(loc++, rest, sym_lst);
105 n.find_ex_by_loc(loc++, coeff, sym_lst);
106 seq.push_back(expair(rest, coeff));
109 n.find_ex("var", var, sym_lst);
110 n.find_ex("point", point, sym_lst);
113 void pseries::archive(archive_node &n) const
115 inherited::archive(n);
116 for (auto & it : seq) {
117 n.add_ex("coeff", it.rest);
118 n.add_ex("power", it.coeff);
120 n.add_ex("var", var);
121 n.add_ex("point", point);
126 // functions overriding virtual functions from base classes
129 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
131 if (precedence() <= level)
134 // objects of type pseries must not have any zero entries, so the
135 // trivial (zero) pseries needs a special treatment here:
139 auto i = seq.begin(), end = seq.end();
142 // print a sign, if needed
143 if (i != seq.begin())
146 if (!is_order_function(i->rest)) {
148 // print 'rest', i.e. the expansion coefficient
149 if (i->rest.info(info_flags::numeric) &&
150 i->rest.info(info_flags::positive)) {
153 c.s << openbrace << '(';
155 c.s << ')' << closebrace;
158 // print 'coeff', something like (x-1)^42
159 if (!i->coeff.is_zero()) {
161 if (!point.is_zero()) {
162 c.s << openbrace << '(';
163 (var-point).print(c);
164 c.s << ')' << closebrace;
167 if (i->coeff.compare(_ex1)) {
170 if (i->coeff.info(info_flags::negative)) {
180 Order(power(var-point,i->coeff)).print(c);
184 if (precedence() <= level)
188 void pseries::do_print(const print_context & c, unsigned level) const
190 print_series(c, "", "", "*", "^", level);
193 void pseries::do_print_latex(const print_latex & c, unsigned level) const
195 print_series(c, "{", "}", " ", "^", level);
198 void pseries::do_print_python(const print_python & c, unsigned level) const
200 print_series(c, "", "", "*", "**", level);
203 void pseries::do_print_tree(const print_tree & c, unsigned level) const
205 c.s << std::string(level, ' ') << class_name() << " @" << this
206 << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
208 size_t num = seq.size();
209 for (size_t i=0; i<num; ++i) {
210 seq[i].rest.print(c, level + c.delta_indent);
211 seq[i].coeff.print(c, level + c.delta_indent);
212 c.s << std::string(level + c.delta_indent, ' ') << "-----" << std::endl;
214 var.print(c, level + c.delta_indent);
215 point.print(c, level + c.delta_indent);
218 void pseries::do_print_python_repr(const print_python_repr & c, unsigned level) const
220 c.s << class_name() << "(relational(";
225 size_t num = seq.size();
226 for (size_t i=0; i<num; ++i) {
230 seq[i].rest.print(c);
232 seq[i].coeff.print(c);
238 int pseries::compare_same_type(const basic & other) const
240 GINAC_ASSERT(is_a<pseries>(other));
241 const pseries &o = static_cast<const pseries &>(other);
243 // first compare the lengths of the series...
244 if (seq.size()>o.seq.size())
246 if (seq.size()<o.seq.size())
249 // ...then the expansion point...
250 int cmpval = var.compare(o.var);
253 cmpval = point.compare(o.point);
257 // ...and if that failed the individual elements
258 epvector::const_iterator it = seq.begin(), o_it = o.seq.begin();
259 while (it!=seq.end() && o_it!=o.seq.end()) {
260 cmpval = it->compare(*o_it);
267 // so they are equal.
271 /** Return the number of operands including a possible order term. */
272 size_t pseries::nops() const
277 /** Return the ith term in the series when represented as a sum. */
278 ex pseries::op(size_t i) const
281 throw (std::out_of_range("op() out of range"));
283 if (is_order_function(seq[i].rest))
284 return Order(power(var-point, seq[i].coeff));
285 return seq[i].rest * power(var - point, seq[i].coeff);
288 /** Return degree of highest power of the series. This is usually the exponent
289 * of the Order term. If s is not the expansion variable of the series, the
290 * series is examined termwise. */
291 int pseries::degree(const ex &s) const
293 if (var.is_equal(s)) {
294 // Return last exponent
296 return ex_to<numeric>((seq.end()-1)->coeff).to_int();
300 epvector::const_iterator it = seq.begin(), itend = seq.end();
303 int max_pow = std::numeric_limits<int>::min();
304 while (it != itend) {
305 int pow = it->rest.degree(s);
314 /** Return degree of lowest power of the series. This is usually the exponent
315 * of the leading term. If s is not the expansion variable of the series, the
316 * series is examined termwise. If s is the expansion variable but the
317 * expansion point is not zero the series is not expanded to find the degree.
318 * I.e.: (1-x) + (1-x)^2 + Order((1-x)^3) has ldegree(x) 1, not 0. */
319 int pseries::ldegree(const ex &s) const
321 if (var.is_equal(s)) {
322 // Return first exponent
324 return ex_to<numeric>((seq.begin())->coeff).to_int();
328 epvector::const_iterator it = seq.begin(), itend = seq.end();
331 int min_pow = std::numeric_limits<int>::max();
332 while (it != itend) {
333 int pow = it->rest.ldegree(s);
342 /** Return coefficient of degree n in power series if s is the expansion
343 * variable. If the expansion point is nonzero, by definition the n=1
344 * coefficient in s of a+b*(s-z)+c*(s-z)^2+Order((s-z)^3) is b (assuming
345 * the expansion took place in the s in the first place).
346 * If s is not the expansion variable, an attempt is made to convert the
347 * series to a polynomial and return the corresponding coefficient from
349 ex pseries::coeff(const ex &s, int n) const
351 if (var.is_equal(s)) {
355 // Binary search in sequence for given power
356 numeric looking_for = numeric(n);
357 int lo = 0, hi = seq.size() - 1;
359 int mid = (lo + hi) / 2;
360 GINAC_ASSERT(is_exactly_a<numeric>(seq[mid].coeff));
361 int cmp = ex_to<numeric>(seq[mid].coeff).compare(looking_for);
367 return seq[mid].rest;
372 throw(std::logic_error("pseries::coeff: compare() didn't return -1, 0 or 1"));
377 return convert_to_poly().coeff(s, n);
381 ex pseries::collect(const ex &s, bool distributed) const
386 /** Perform coefficient-wise automatic term rewriting rules in this class. */
387 ex pseries::eval(int level) const
392 if (level == -max_recursion_level)
393 throw (std::runtime_error("pseries::eval(): recursion limit exceeded"));
395 // Construct a new series with evaluated coefficients
397 new_seq.reserve(seq.size());
398 epvector::const_iterator it = seq.begin(), itend = seq.end();
399 while (it != itend) {
400 new_seq.push_back(expair(it->rest.eval(level-1), it->coeff));
403 return dynallocate<pseries>(relational(var,point), std::move(new_seq)).setflag(status_flags::evaluated);
406 /** Evaluate coefficients numerically. */
407 ex pseries::evalf(int level) const
412 if (level == -max_recursion_level)
413 throw (std::runtime_error("pseries::evalf(): recursion limit exceeded"));
415 // Construct a new series with evaluated coefficients
417 new_seq.reserve(seq.size());
418 epvector::const_iterator it = seq.begin(), itend = seq.end();
419 while (it != itend) {
420 new_seq.push_back(expair(it->rest.evalf(level-1), it->coeff));
423 return dynallocate<pseries>(relational(var,point), std::move(new_seq)).setflag(status_flags::evaluated);
426 ex pseries::conjugate() const
428 if(!var.info(info_flags::real))
429 return conjugate_function(*this).hold();
431 std::unique_ptr<epvector> newseq(conjugateepvector(seq));
432 ex newpoint = point.conjugate();
434 if (!newseq && are_ex_trivially_equal(point, newpoint)) {
438 return dynallocate<pseries>(var==newpoint, newseq ? std::move(*newseq) : seq);
441 ex pseries::real_part() const
443 if(!var.info(info_flags::real))
444 return real_part_function(*this).hold();
445 ex newpoint = point.real_part();
446 if(newpoint != point)
447 return real_part_function(*this).hold();
450 v.reserve(seq.size());
451 for (auto & it : seq)
452 v.push_back(expair((it.rest).real_part(), it.coeff));
453 return dynallocate<pseries>(var==point, std::move(v));
456 ex pseries::imag_part() const
458 if(!var.info(info_flags::real))
459 return imag_part_function(*this).hold();
460 ex newpoint = point.real_part();
461 if(newpoint != point)
462 return imag_part_function(*this).hold();
465 v.reserve(seq.size());
466 for (auto & it : seq)
467 v.push_back(expair((it.rest).imag_part(), it.coeff));
468 return dynallocate<pseries>(var==point, std::move(v));
471 ex pseries::eval_integ() const
473 std::unique_ptr<epvector> newseq(nullptr);
474 for (auto i=seq.begin(); i!=seq.end(); ++i) {
476 newseq->push_back(expair(i->rest.eval_integ(), i->coeff));
479 ex newterm = i->rest.eval_integ();
480 if (!are_ex_trivially_equal(newterm, i->rest)) {
481 newseq.reset(new epvector);
482 newseq->reserve(seq.size());
483 for (auto j=seq.begin(); j!=i; ++j)
484 newseq->push_back(*j);
485 newseq->push_back(expair(newterm, i->coeff));
489 ex newpoint = point.eval_integ();
490 if (newseq || !are_ex_trivially_equal(newpoint, point))
491 return dynallocate<pseries>(var==newpoint, std::move(*newseq));
495 ex pseries::evalm() const
497 // evalm each coefficient
499 bool something_changed = false;
500 for (auto i=seq.begin(); i!=seq.end(); ++i) {
501 if (something_changed) {
502 ex newcoeff = i->rest.evalm();
503 if (!newcoeff.is_zero())
504 newseq.push_back(expair(newcoeff, i->coeff));
507 ex newcoeff = i->rest.evalm();
508 if (!are_ex_trivially_equal(newcoeff, i->rest)) {
509 something_changed = true;
510 newseq.reserve(seq.size());
511 std::copy(seq.begin(), i, std::back_inserter<epvector>(newseq));
512 if (!newcoeff.is_zero())
513 newseq.push_back(expair(newcoeff, i->coeff));
517 if (something_changed)
518 return dynallocate<pseries>(var==point, std::move(newseq));
523 ex pseries::subs(const exmap & m, unsigned options) const
525 // If expansion variable is being substituted, convert the series to a
526 // polynomial and do the substitution there because the result might
527 // no longer be a power series
528 if (m.find(var) != m.end())
529 return convert_to_poly(true).subs(m, options);
531 // Otherwise construct a new series with substituted coefficients and
534 newseq.reserve(seq.size());
535 for (auto & it : seq)
536 newseq.push_back(expair(it.rest.subs(m, options), it.coeff));
537 return dynallocate<pseries>(relational(var,point.subs(m, options)), std::move(newseq));
540 /** Implementation of ex::expand() for a power series. It expands all the
541 * terms individually and returns the resulting series as a new pseries. */
542 ex pseries::expand(unsigned options) const
545 for (auto & it : seq) {
546 ex restexp = it.rest.expand();
547 if (!restexp.is_zero())
548 newseq.push_back(expair(restexp, it.coeff));
550 return dynallocate<pseries>(relational(var,point), std::move(newseq)).setflag(options == 0 ? status_flags::expanded : 0);
553 /** Implementation of ex::diff() for a power series.
555 ex pseries::derivative(const symbol & s) const
561 // FIXME: coeff might depend on var
562 for (auto & it : seq) {
563 if (is_order_function(it.rest)) {
564 new_seq.push_back(expair(it.rest, it.coeff - 1));
566 ex c = it.rest * it.coeff;
568 new_seq.push_back(expair(c, it.coeff - 1));
574 for (auto & it : seq) {
575 if (is_order_function(it.rest)) {
576 new_seq.push_back(it);
578 ex c = it.rest.diff(s);
580 new_seq.push_back(expair(c, it.coeff));
585 return pseries(relational(var,point), std::move(new_seq));
588 ex pseries::convert_to_poly(bool no_order) const
591 for (auto & it : seq) {
592 if (is_order_function(it.rest)) {
594 e += Order(power(var - point, it.coeff));
596 e += it.rest * power(var - point, it.coeff);
601 bool pseries::is_terminating() const
603 return seq.empty() || !is_order_function((seq.end()-1)->rest);
606 ex pseries::coeffop(size_t i) const
609 throw (std::out_of_range("coeffop() out of range"));
613 ex pseries::exponop(size_t i) const
616 throw (std::out_of_range("exponop() out of range"));
622 * Implementations of series expansion
625 /** Default implementation of ex::series(). This performs Taylor expansion.
627 ex basic::series(const relational & r, int order, unsigned options) const
630 const symbol &s = ex_to<symbol>(r.lhs());
632 // default for order-values that make no sense for Taylor expansion
633 if ((order <= 0) && this->has(s)) {
634 seq.push_back(expair(Order(_ex1), order));
635 return pseries(r, std::move(seq));
638 // do Taylor expansion
641 ex coeff = deriv.subs(r, subs_options::no_pattern);
643 if (!coeff.is_zero()) {
644 seq.push_back(expair(coeff, _ex0));
648 for (n=1; n<order; ++n) {
650 // We need to test for zero in order to see if the series terminates.
651 // The problem is that there is no such thing as a perfect test for
652 // zero. Expanding the term occasionally helps a little...
653 deriv = deriv.diff(s).expand();
654 if (deriv.is_zero()) // Series terminates
655 return pseries(r, std::move(seq));
657 coeff = deriv.subs(r, subs_options::no_pattern);
658 if (!coeff.is_zero())
659 seq.push_back(expair(fac.inverse() * coeff, n));
662 // Higher-order terms, if present
663 deriv = deriv.diff(s);
664 if (!deriv.expand().is_zero())
665 seq.push_back(expair(Order(_ex1), n));
666 return pseries(r, std::move(seq));
670 /** Implementation of ex::series() for symbols.
672 ex symbol::series(const relational & r, int order, unsigned options) const
675 const ex point = r.rhs();
676 GINAC_ASSERT(is_a<symbol>(r.lhs()));
678 if (this->is_equal_same_type(ex_to<symbol>(r.lhs()))) {
679 if (order > 0 && !point.is_zero())
680 seq.push_back(expair(point, _ex0));
682 seq.push_back(expair(_ex1, _ex1));
684 seq.push_back(expair(Order(_ex1), numeric(order)));
686 seq.push_back(expair(*this, _ex0));
687 return pseries(r, std::move(seq));
691 /** Add one series object to another, producing a pseries object that
692 * represents the sum.
694 * @param other pseries object to add with
695 * @return the sum as a pseries */
696 ex pseries::add_series(const pseries &other) const
698 // Adding two series with different variables or expansion points
699 // results in an empty (constant) series
700 if (!is_compatible_to(other)) {
701 epvector nul { expair(Order(_ex1), _ex0) };
702 return pseries(relational(var,point), std::move(nul));
707 auto a = seq.begin(), a_end = seq.end();
708 auto b = other.seq.begin(), b_end = other.seq.end();
709 int pow_a = std::numeric_limits<int>::max(), pow_b = std::numeric_limits<int>::max();
711 // If a is empty, fill up with elements from b and stop
714 new_seq.push_back(*b);
719 pow_a = ex_to<numeric>((*a).coeff).to_int();
721 // If b is empty, fill up with elements from a and stop
724 new_seq.push_back(*a);
729 pow_b = ex_to<numeric>((*b).coeff).to_int();
731 // a and b are non-empty, compare powers
733 // a has lesser power, get coefficient from a
734 new_seq.push_back(*a);
735 if (is_order_function((*a).rest))
738 } else if (pow_b < pow_a) {
739 // b has lesser power, get coefficient from b
740 new_seq.push_back(*b);
741 if (is_order_function((*b).rest))
745 // Add coefficient of a and b
746 if (is_order_function((*a).rest) || is_order_function((*b).rest)) {
747 new_seq.push_back(expair(Order(_ex1), (*a).coeff));
748 break; // Order term ends the sequence
750 ex sum = (*a).rest + (*b).rest;
751 if (!(sum.is_zero()))
752 new_seq.push_back(expair(sum, numeric(pow_a)));
758 return pseries(relational(var,point), std::move(new_seq));
762 /** Implementation of ex::series() for sums. This performs series addition when
763 * adding pseries objects.
765 ex add::series(const relational & r, int order, unsigned options) const
767 ex acc; // Series accumulator
769 // Get first term from overall_coeff
770 acc = overall_coeff.series(r, order, options);
772 // Add remaining terms
773 for (auto & it : seq) {
775 if (is_exactly_a<pseries>(it.rest))
778 op = it.rest.series(r, order, options);
779 if (!it.coeff.is_equal(_ex1))
780 op = ex_to<pseries>(op).mul_const(ex_to<numeric>(it.coeff));
783 acc = ex_to<pseries>(acc).add_series(ex_to<pseries>(op));
789 /** Multiply a pseries object with a numeric constant, producing a pseries
790 * object that represents the product.
792 * @param other constant to multiply with
793 * @return the product as a pseries */
794 ex pseries::mul_const(const numeric &other) const
797 new_seq.reserve(seq.size());
799 for (auto & it : seq) {
800 if (!is_order_function(it.rest))
801 new_seq.push_back(expair(it.rest * other, it.coeff));
803 new_seq.push_back(it);
805 return pseries(relational(var,point), std::move(new_seq));
809 /** Multiply one pseries object to another, producing a pseries object that
810 * represents the product.
812 * @param other pseries object to multiply with
813 * @return the product as a pseries */
814 ex pseries::mul_series(const pseries &other) const
816 // Multiplying two series with different variables or expansion points
817 // results in an empty (constant) series
818 if (!is_compatible_to(other)) {
819 epvector nul { expair(Order(_ex1), _ex0) };
820 return pseries(relational(var,point), std::move(nul));
823 if (seq.empty() || other.seq.empty()) {
824 return dynallocate<pseries>(var==point, epvector());
827 // Series multiplication
829 int a_max = degree(var);
830 int b_max = other.degree(var);
831 int a_min = ldegree(var);
832 int b_min = other.ldegree(var);
833 int cdeg_min = a_min + b_min;
834 int cdeg_max = a_max + b_max;
836 int higher_order_a = std::numeric_limits<int>::max();
837 int higher_order_b = std::numeric_limits<int>::max();
838 if (is_order_function(coeff(var, a_max)))
839 higher_order_a = a_max + b_min;
840 if (is_order_function(other.coeff(var, b_max)))
841 higher_order_b = b_max + a_min;
842 int higher_order_c = std::min(higher_order_a, higher_order_b);
843 if (cdeg_max >= higher_order_c)
844 cdeg_max = higher_order_c - 1;
846 for (int cdeg=cdeg_min; cdeg<=cdeg_max; ++cdeg) {
848 // c(i)=a(0)b(i)+...+a(i)b(0)
849 for (int i=a_min; cdeg-i>=b_min; ++i) {
850 ex a_coeff = coeff(var, i);
851 ex b_coeff = other.coeff(var, cdeg-i);
852 if (!is_order_function(a_coeff) && !is_order_function(b_coeff))
853 co += a_coeff * b_coeff;
856 new_seq.push_back(expair(co, numeric(cdeg)));
858 if (higher_order_c < std::numeric_limits<int>::max())
859 new_seq.push_back(expair(Order(_ex1), numeric(higher_order_c)));
860 return pseries(relational(var, point), std::move(new_seq));
864 /** Implementation of ex::series() for product. This performs series
865 * multiplication when multiplying series.
867 ex mul::series(const relational & r, int order, unsigned options) const
869 pseries acc; // Series accumulator
871 GINAC_ASSERT(is_a<symbol>(r.lhs()));
872 const ex& sym = r.lhs();
874 // holds ldegrees of the series of individual factors
875 std::vector<int> ldegrees;
876 std::vector<bool> ldegree_redo;
878 // find minimal degrees
879 // first round: obtain a bound up to which minimal degrees have to be
881 for (auto & it : seq) {
886 if (expon.info(info_flags::integer)) {
888 factor = ex_to<numeric>(expon).to_int();
890 buf = recombine_pair_to_ex(it);
893 int real_ldegree = 0;
894 bool flag_redo = false;
896 real_ldegree = buf.expand().ldegree(sym-r.rhs());
897 } catch (std::runtime_error) {}
899 if (real_ldegree == 0) {
901 // This case must terminate, otherwise we would have division by
906 real_ldegree = buf.series(r, orderloop, options).ldegree(sym);
907 } while (real_ldegree == orderloop);
909 // Here it is possible that buf does not have a ldegree, therefore
910 // check only if ldegree is negative, otherwise reconsider the case
911 // in the second round.
912 real_ldegree = buf.series(r, 0, options).ldegree(sym);
913 if (real_ldegree == 0)
918 ldegrees.push_back(factor * real_ldegree);
919 ldegree_redo.push_back(flag_redo);
922 int degbound = order-std::accumulate(ldegrees.begin(), ldegrees.end(), 0);
923 // Second round: determine the remaining positive ldegrees by the series
925 // here we can ignore ldegrees larger than degbound
927 for (auto & it : seq) {
928 if ( ldegree_redo[j] ) {
932 if (expon.info(info_flags::integer)) {
934 factor = ex_to<numeric>(expon).to_int();
936 buf = recombine_pair_to_ex(it);
938 int real_ldegree = 0;
942 real_ldegree = buf.series(r, orderloop, options).ldegree(sym);
943 } while ((real_ldegree == orderloop)
944 && (factor*real_ldegree < degbound));
945 ldegrees[j] = factor * real_ldegree;
946 degbound -= factor * real_ldegree;
951 int degsum = std::accumulate(ldegrees.begin(), ldegrees.end(), 0);
953 if (degsum >= order) {
954 epvector epv { expair(Order(_ex1), order) };
955 return dynallocate<pseries>(r, std::move(epv));
958 // Multiply with remaining terms
959 auto itd = ldegrees.begin();
960 for (auto it=seq.begin(), itend=seq.end(); it!=itend; ++it, ++itd) {
962 // do series expansion with adjusted order
963 ex op = recombine_pair_to_ex(*it).series(r, order-degsum+(*itd), options);
965 // Series multiplication
966 if (it == seq.begin())
967 acc = ex_to<pseries>(op);
969 acc = ex_to<pseries>(acc.mul_series(ex_to<pseries>(op)));
972 return acc.mul_const(ex_to<numeric>(overall_coeff));
976 /** Compute the p-th power of a series.
978 * @param p power to compute
979 * @param deg truncation order of series calculation */
980 ex pseries::power_const(const numeric &p, int deg) const
983 // (due to Leonhard Euler)
984 // let A(x) be this series and for the time being let it start with a
985 // constant (later we'll generalize):
986 // A(x) = a_0 + a_1*x + a_2*x^2 + ...
987 // We want to compute
989 // C(x) = c_0 + c_1*x + c_2*x^2 + ...
990 // Taking the derivative on both sides and multiplying with A(x) one
991 // immediately arrives at
992 // C'(x)*A(x) = p*C(x)*A'(x)
993 // Multiplying this out and comparing coefficients we get the recurrence
995 // c_i = (i*p*a_i*c_0 + ((i-1)*p-1)*a_{i-1}*c_1 + ...
996 // ... + (p-(i-1))*a_1*c_{i-1})/(a_0*i)
997 // which can easily be solved given the starting value c_0 = (a_0)^p.
998 // For the more general case where the leading coefficient of A(x) is not
999 // a constant, just consider A2(x) = A(x)*x^m, with some integer m and
1000 // repeat the above derivation. The leading power of C2(x) = A2(x)^2 is
1001 // then of course x^(p*m) but the recurrence formula still holds.
1004 // as a special case, handle the empty (zero) series honoring the
1005 // usual power laws such as implemented in power::eval()
1006 if (p.real().is_zero())
1007 throw std::domain_error("pseries::power_const(): pow(0,I) is undefined");
1008 else if (p.real().is_negative())
1009 throw pole_error("pseries::power_const(): division by zero",1);
1014 const int ldeg = ldegree(var);
1015 if (!(p*ldeg).is_integer())
1016 throw std::runtime_error("pseries::power_const(): trying to assemble a Puiseux series");
1018 // adjust number of coefficients
1019 int numcoeff = deg - (p*ldeg).to_int();
1020 if (numcoeff <= 0) {
1021 epvector epv { expair(Order(_ex1), deg) };
1022 return dynallocate<pseries>(relational(var,point), std::move(epv));
1025 // O(x^n)^(-m) is undefined
1026 if (seq.size() == 1 && is_order_function(seq[0].rest) && p.real().is_negative())
1027 throw pole_error("pseries::power_const(): division by zero",1);
1029 // Compute coefficients of the powered series
1031 co.reserve(numcoeff);
1032 co.push_back(power(coeff(var, ldeg), p));
1033 for (int i=1; i<numcoeff; ++i) {
1035 for (int j=1; j<=i; ++j) {
1036 ex c = coeff(var, j + ldeg);
1037 if (is_order_function(c)) {
1038 co.push_back(Order(_ex1));
1041 sum += (p * j - (i - j)) * co[i - j] * c;
1043 co.push_back(sum / coeff(var, ldeg) / i);
1046 // Construct new series (of non-zero coefficients)
1048 bool higher_order = false;
1049 for (int i=0; i<numcoeff; ++i) {
1050 if (!co[i].is_zero())
1051 new_seq.push_back(expair(co[i], p * ldeg + i));
1052 if (is_order_function(co[i])) {
1053 higher_order = true;
1058 new_seq.push_back(expair(Order(_ex1), p * ldeg + numcoeff));
1060 return pseries(relational(var,point), std::move(new_seq));
1064 /** Return a new pseries object with the powers shifted by deg. */
1065 pseries pseries::shift_exponents(int deg) const
1067 epvector newseq = seq;
1068 for (auto & it : newseq)
1070 return pseries(relational(var, point), std::move(newseq));
1074 /** Implementation of ex::series() for powers. This performs Laurent expansion
1075 * of reciprocals of series at singularities.
1076 * @see ex::series */
1077 ex power::series(const relational & r, int order, unsigned options) const
1079 // If basis is already a series, just power it
1080 if (is_exactly_a<pseries>(basis))
1081 return ex_to<pseries>(basis).power_const(ex_to<numeric>(exponent), order);
1083 // Basis is not a series, may there be a singularity?
1084 bool must_expand_basis = false;
1086 basis.subs(r, subs_options::no_pattern);
1087 } catch (pole_error) {
1088 must_expand_basis = true;
1091 bool exponent_is_regular = true;
1093 exponent.subs(r, subs_options::no_pattern);
1094 } catch (pole_error) {
1095 exponent_is_regular = false;
1098 if (!exponent_is_regular) {
1099 ex l = exponent*log(basis);
1101 ex le = l.series(r, order, options);
1102 // Note: expanding exp(l) won't help, since that will attempt
1103 // Taylor expansion, and fail (because exponent is "singular")
1104 // Still l itself might be expanded in Taylor series.
1106 // sin(x)/x*log(cos(x))
1108 return exp(le).series(r, order, options);
1109 // Note: if l happens to have a Laurent expansion (with
1110 // negative powers of (var - point)), expanding exp(le)
1111 // will barf (which is The Right Thing).
1114 // Is the expression of type something^(-int)?
1115 if (!must_expand_basis && !exponent.info(info_flags::negint)
1116 && (!is_a<add>(basis) || !is_a<numeric>(exponent)))
1117 return basic::series(r, order, options);
1119 // Is the expression of type 0^something?
1120 if (!must_expand_basis && !basis.subs(r, subs_options::no_pattern).is_zero()
1121 && (!is_a<add>(basis) || !is_a<numeric>(exponent)))
1122 return basic::series(r, order, options);
1124 // Singularity encountered, is the basis equal to (var - point)?
1125 if (basis.is_equal(r.lhs() - r.rhs())) {
1127 if (ex_to<numeric>(exponent).to_int() < order)
1128 new_seq.push_back(expair(_ex1, exponent));
1130 new_seq.push_back(expair(Order(_ex1), exponent));
1131 return pseries(r, std::move(new_seq));
1134 // No, expand basis into series
1137 if (is_a<numeric>(exponent)) {
1138 numexp = ex_to<numeric>(exponent);
1142 const ex& sym = r.lhs();
1143 // find existing minimal degree
1144 ex eb = basis.expand();
1145 int real_ldegree = 0;
1146 if (eb.info(info_flags::rational_function))
1147 real_ldegree = eb.ldegree(sym-r.rhs());
1148 if (real_ldegree == 0) {
1152 real_ldegree = basis.series(r, orderloop, options).ldegree(sym);
1153 } while (real_ldegree == orderloop);
1156 if (!(real_ldegree*numexp).is_integer())
1157 throw std::runtime_error("pseries::power_const(): trying to assemble a Puiseux series");
1158 ex e = basis.series(r, (order + real_ldegree*(1-numexp)).to_int(), options);
1162 result = ex_to<pseries>(e).power_const(numexp, order);
1163 } catch (pole_error) {
1164 epvector ser { expair(Order(_ex1), order) };
1165 result = pseries(r, std::move(ser));
1172 /** Re-expansion of a pseries object. */
1173 ex pseries::series(const relational & r, int order, unsigned options) const
1175 const ex p = r.rhs();
1176 GINAC_ASSERT(is_a<symbol>(r.lhs()));
1177 const symbol &s = ex_to<symbol>(r.lhs());
1179 if (var.is_equal(s) && point.is_equal(p)) {
1180 if (order > degree(s))
1184 for (auto & it : seq) {
1185 int o = ex_to<numeric>(it.coeff).to_int();
1187 new_seq.push_back(expair(Order(_ex1), o));
1190 new_seq.push_back(it);
1192 return pseries(r, std::move(new_seq));
1195 return convert_to_poly().series(r, order, options);
1198 ex integral::series(const relational & r, int order, unsigned options) const
1201 throw std::logic_error("Cannot series expand wrt dummy variable");
1203 // Expanding integrand with r substituted taken in boundaries.
1204 ex fseries = f.series(r, order, options);
1205 epvector fexpansion;
1206 fexpansion.reserve(fseries.nops());
1207 for (size_t i=0; i<fseries.nops(); ++i) {
1208 ex currcoeff = ex_to<pseries>(fseries).coeffop(i);
1209 currcoeff = (currcoeff == Order(_ex1))
1211 : integral(x, a.subs(r), b.subs(r), currcoeff);
1213 fexpansion.push_back(
1214 expair(currcoeff, ex_to<pseries>(fseries).exponop(i)));
1217 // Expanding lower boundary
1218 ex result = dynallocate<pseries>(r, std::move(fexpansion));
1219 ex aseries = (a-a.subs(r)).series(r, order, options);
1220 fseries = f.series(x == (a.subs(r)), order, options);
1221 for (size_t i=0; i<fseries.nops(); ++i) {
1222 ex currcoeff = ex_to<pseries>(fseries).coeffop(i);
1223 if (is_order_function(currcoeff))
1225 ex currexpon = ex_to<pseries>(fseries).exponop(i);
1226 int orderforf = order-ex_to<numeric>(currexpon).to_int()-1;
1227 currcoeff = currcoeff.series(r, orderforf);
1228 ex term = ex_to<pseries>(aseries).power_const(ex_to<numeric>(currexpon+1),order);
1229 term = ex_to<pseries>(term).mul_const(ex_to<numeric>(-1/(currexpon+1)));
1230 term = ex_to<pseries>(term).mul_series(ex_to<pseries>(currcoeff));
1231 result = ex_to<pseries>(result).add_series(ex_to<pseries>(term));
1234 // Expanding upper boundary
1235 ex bseries = (b-b.subs(r)).series(r, order, options);
1236 fseries = f.series(x == (b.subs(r)), order, options);
1237 for (size_t i=0; i<fseries.nops(); ++i) {
1238 ex currcoeff = ex_to<pseries>(fseries).coeffop(i);
1239 if (is_order_function(currcoeff))
1241 ex currexpon = ex_to<pseries>(fseries).exponop(i);
1242 int orderforf = order-ex_to<numeric>(currexpon).to_int()-1;
1243 currcoeff = currcoeff.series(r, orderforf);
1244 ex term = ex_to<pseries>(bseries).power_const(ex_to<numeric>(currexpon+1),order);
1245 term = ex_to<pseries>(term).mul_const(ex_to<numeric>(1/(currexpon+1)));
1246 term = ex_to<pseries>(term).mul_series(ex_to<pseries>(currcoeff));
1247 result = ex_to<pseries>(result).add_series(ex_to<pseries>(term));
1254 /** Compute the truncated series expansion of an expression.
1255 * This function returns an expression containing an object of class pseries
1256 * to represent the series. If the series does not terminate within the given
1257 * truncation order, the last term of the series will be an order term.
1259 * @param r expansion relation, lhs holds variable and rhs holds point
1260 * @param order truncation order of series calculations
1261 * @param options of class series_options
1262 * @return an expression holding a pseries object */
1263 ex ex::series(const ex & r, int order, unsigned options) const
1268 if (is_a<relational>(r))
1269 rel_ = ex_to<relational>(r);
1270 else if (is_a<symbol>(r))
1271 rel_ = relational(r,_ex0);
1273 throw (std::logic_error("ex::series(): expansion point has unknown type"));
1275 e = bp->series(rel_, order, options);
1279 GINAC_BIND_UNARCHIVER(pseries);
1281 } // namespace GiNaC