3 * Implementation of class for extended truncated power series and
4 * methods for series expansion. */
7 * GiNaC Copyright (C) 1999-2007 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
30 #include "inifcns.h" // for Order function
34 #include "relational.h"
35 #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() : inherited(&pseries::tinfo_static) { }
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_) : basic(&pseries::tinfo_static), seq(ops_)
73 GINAC_ASSERT(is_a<relational>(rel_));
74 GINAC_ASSERT(is_a<symbol>(rel_.lhs()));
84 pseries::pseries(const archive_node &n, lst &sym_lst) : inherited(n, sym_lst)
86 archive_node::archive_node_cit first = n.find_first("coeff");
87 archive_node::archive_node_cit last = n.find_last("power");
89 seq.reserve((last-first)/2);
91 for (archive_node::archive_node_cit loc = first; loc < last;) {
94 n.find_ex_by_loc(loc++, rest, sym_lst);
95 n.find_ex_by_loc(loc++, coeff, sym_lst);
96 seq.push_back(expair(rest, coeff));
99 n.find_ex("var", var, sym_lst);
100 n.find_ex("point", point, sym_lst);
103 void pseries::archive(archive_node &n) const
105 inherited::archive(n);
106 epvector::const_iterator i = seq.begin(), iend = seq.end();
108 n.add_ex("coeff", i->rest);
109 n.add_ex("power", i->coeff);
112 n.add_ex("var", var);
113 n.add_ex("point", point);
116 DEFAULT_UNARCHIVE(pseries)
119 // functions overriding virtual functions from base classes
122 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
124 if (precedence() <= level)
127 // objects of type pseries must not have any zero entries, so the
128 // trivial (zero) pseries needs a special treatment here:
132 epvector::const_iterator i = seq.begin(), end = seq.end();
135 // print a sign, if needed
136 if (i != seq.begin())
139 if (!is_order_function(i->rest)) {
141 // print 'rest', i.e. the expansion coefficient
142 if (i->rest.info(info_flags::numeric) &&
143 i->rest.info(info_flags::positive)) {
146 c.s << openbrace << '(';
148 c.s << ')' << closebrace;
151 // print 'coeff', something like (x-1)^42
152 if (!i->coeff.is_zero()) {
154 if (!point.is_zero()) {
155 c.s << openbrace << '(';
156 (var-point).print(c);
157 c.s << ')' << closebrace;
160 if (i->coeff.compare(_ex1)) {
163 if (i->coeff.info(info_flags::negative)) {
173 Order(power(var-point,i->coeff)).print(c);
177 if (precedence() <= level)
181 void pseries::do_print(const print_context & c, unsigned level) const
183 print_series(c, "", "", "*", "^", level);
186 void pseries::do_print_latex(const print_latex & c, unsigned level) const
188 print_series(c, "{", "}", " ", "^", level);
191 void pseries::do_print_python(const print_python & c, unsigned level) const
193 print_series(c, "", "", "*", "**", level);
196 void pseries::do_print_tree(const print_tree & c, unsigned level) const
198 c.s << std::string(level, ' ') << class_name() << " @" << this
199 << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
201 size_t num = seq.size();
202 for (size_t i=0; i<num; ++i) {
203 seq[i].rest.print(c, level + c.delta_indent);
204 seq[i].coeff.print(c, level + c.delta_indent);
205 c.s << std::string(level + c.delta_indent, ' ') << "-----" << std::endl;
207 var.print(c, level + c.delta_indent);
208 point.print(c, level + c.delta_indent);
211 void pseries::do_print_python_repr(const print_python_repr & c, unsigned level) const
213 c.s << class_name() << "(relational(";
218 size_t num = seq.size();
219 for (size_t i=0; i<num; ++i) {
223 seq[i].rest.print(c);
225 seq[i].coeff.print(c);
231 int pseries::compare_same_type(const basic & other) const
233 GINAC_ASSERT(is_a<pseries>(other));
234 const pseries &o = static_cast<const pseries &>(other);
236 // first compare the lengths of the series...
237 if (seq.size()>o.seq.size())
239 if (seq.size()<o.seq.size())
242 // ...then the expansion point...
243 int cmpval = var.compare(o.var);
246 cmpval = point.compare(o.point);
250 // ...and if that failed the individual elements
251 epvector::const_iterator it = seq.begin(), o_it = o.seq.begin();
252 while (it!=seq.end() && o_it!=o.seq.end()) {
253 cmpval = it->compare(*o_it);
260 // so they are equal.
264 /** Return the number of operands including a possible order term. */
265 size_t pseries::nops() const
270 /** Return the ith term in the series when represented as a sum. */
271 ex pseries::op(size_t i) const
274 throw (std::out_of_range("op() out of range"));
276 if (is_order_function(seq[i].rest))
277 return Order(power(var-point, seq[i].coeff));
278 return seq[i].rest * power(var - point, seq[i].coeff);
281 /** Return degree of highest power of the series. This is usually the exponent
282 * of the Order term. If s is not the expansion variable of the series, the
283 * series is examined termwise. */
284 int pseries::degree(const ex &s) const
286 if (var.is_equal(s)) {
287 // Return last exponent
289 return ex_to<numeric>((seq.end()-1)->coeff).to_int();
293 epvector::const_iterator it = seq.begin(), itend = seq.end();
296 int max_pow = std::numeric_limits<int>::min();
297 while (it != itend) {
298 int pow = it->rest.degree(s);
307 /** Return degree of lowest power of the series. This is usually the exponent
308 * of the leading term. If s is not the expansion variable of the series, the
309 * series is examined termwise. If s is the expansion variable but the
310 * expansion point is not zero the series is not expanded to find the degree.
311 * I.e.: (1-x) + (1-x)^2 + Order((1-x)^3) has ldegree(x) 1, not 0. */
312 int pseries::ldegree(const ex &s) const
314 if (var.is_equal(s)) {
315 // Return first exponent
317 return ex_to<numeric>((seq.begin())->coeff).to_int();
321 epvector::const_iterator it = seq.begin(), itend = seq.end();
324 int min_pow = std::numeric_limits<int>::max();
325 while (it != itend) {
326 int pow = it->rest.ldegree(s);
335 /** Return coefficient of degree n in power series if s is the expansion
336 * variable. If the expansion point is nonzero, by definition the n=1
337 * coefficient in s of a+b*(s-z)+c*(s-z)^2+Order((s-z)^3) is b (assuming
338 * the expansion took place in the s in the first place).
339 * If s is not the expansion variable, an attempt is made to convert the
340 * series to a polynomial and return the corresponding coefficient from
342 ex pseries::coeff(const ex &s, int n) const
344 if (var.is_equal(s)) {
348 // Binary search in sequence for given power
349 numeric looking_for = numeric(n);
350 int lo = 0, hi = seq.size() - 1;
352 int mid = (lo + hi) / 2;
353 GINAC_ASSERT(is_exactly_a<numeric>(seq[mid].coeff));
354 int cmp = ex_to<numeric>(seq[mid].coeff).compare(looking_for);
360 return seq[mid].rest;
365 throw(std::logic_error("pseries::coeff: compare() didn't return -1, 0 or 1"));
370 return convert_to_poly().coeff(s, n);
374 ex pseries::collect(const ex &s, bool distributed) const
379 /** Perform coefficient-wise automatic term rewriting rules in this class. */
380 ex pseries::eval(int level) const
385 if (level == -max_recursion_level)
386 throw (std::runtime_error("pseries::eval(): recursion limit exceeded"));
388 // Construct a new series with evaluated coefficients
390 new_seq.reserve(seq.size());
391 epvector::const_iterator it = seq.begin(), itend = seq.end();
392 while (it != itend) {
393 new_seq.push_back(expair(it->rest.eval(level-1), it->coeff));
396 return (new pseries(relational(var,point), new_seq))->setflag(status_flags::dynallocated | status_flags::evaluated);
399 /** Evaluate coefficients numerically. */
400 ex pseries::evalf(int level) const
405 if (level == -max_recursion_level)
406 throw (std::runtime_error("pseries::evalf(): recursion limit exceeded"));
408 // Construct a new series with evaluated coefficients
410 new_seq.reserve(seq.size());
411 epvector::const_iterator it = seq.begin(), itend = seq.end();
412 while (it != itend) {
413 new_seq.push_back(expair(it->rest.evalf(level-1), it->coeff));
416 return (new pseries(relational(var,point), new_seq))->setflag(status_flags::dynallocated | status_flags::evaluated);
419 ex pseries::conjugate() const
421 if(!var.info(info_flags::real))
422 return conjugate_function(*this).hold();
424 epvector * newseq = conjugateepvector(seq);
425 ex newpoint = point.conjugate();
427 if (!newseq && are_ex_trivially_equal(point, newpoint)) {
431 ex result = (new pseries(var==newpoint, newseq ? *newseq : seq))->setflag(status_flags::dynallocated);
438 ex pseries::real_part() const
440 if(!var.info(info_flags::real))
441 return real_part_function(*this).hold();
442 ex newpoint = point.real_part();
443 if(newpoint != point)
444 return real_part_function(*this).hold();
447 v.reserve(seq.size());
448 for(epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i)
449 v.push_back(expair((i->rest).real_part(), i->coeff));
450 return (new pseries(var==point, v))->setflag(status_flags::dynallocated);
453 ex pseries::imag_part() const
455 if(!var.info(info_flags::real))
456 return imag_part_function(*this).hold();
457 ex newpoint = point.real_part();
458 if(newpoint != point)
459 return imag_part_function(*this).hold();
462 v.reserve(seq.size());
463 for(epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i)
464 v.push_back(expair((i->rest).imag_part(), i->coeff));
465 return (new pseries(var==point, v))->setflag(status_flags::dynallocated);
468 ex pseries::eval_integ() const
470 epvector *newseq = NULL;
471 for (epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i) {
473 newseq->push_back(expair(i->rest.eval_integ(), i->coeff));
476 ex newterm = i->rest.eval_integ();
477 if (!are_ex_trivially_equal(newterm, i->rest)) {
478 newseq = new epvector;
479 newseq->reserve(seq.size());
480 for (epvector::const_iterator j=seq.begin(); j!=i; ++j)
481 newseq->push_back(*j);
482 newseq->push_back(expair(newterm, i->coeff));
486 ex newpoint = point.eval_integ();
487 if (newseq || !are_ex_trivially_equal(newpoint, point))
488 return (new pseries(var==newpoint, *newseq))
489 ->setflag(status_flags::dynallocated);
493 ex pseries::evalm() const
495 // evalm each coefficient
497 bool something_changed = false;
498 for (epvector::const_iterator 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));
505 ex newcoeff = i->rest.evalm();
506 if (!are_ex_trivially_equal(newcoeff, i->rest)) {
507 something_changed = true;
508 newseq.reserve(seq.size());
509 std::copy(seq.begin(), i, std::back_inserter<epvector>(newseq));
510 if (!newcoeff.is_zero())
511 newseq.push_back(expair(newcoeff, i->coeff));
515 if (something_changed)
516 return (new pseries(var==point, newseq))->setflag(status_flags::dynallocated);
521 ex pseries::subs(const exmap & m, unsigned options) const
523 // If expansion variable is being substituted, convert the series to a
524 // polynomial and do the substitution there because the result might
525 // no longer be a power series
526 if (m.find(var) != m.end())
527 return convert_to_poly(true).subs(m, options);
529 // Otherwise construct a new series with substituted coefficients and
532 newseq.reserve(seq.size());
533 epvector::const_iterator it = seq.begin(), itend = seq.end();
534 while (it != itend) {
535 newseq.push_back(expair(it->rest.subs(m, options), it->coeff));
538 return (new pseries(relational(var,point.subs(m, options)), newseq))->setflag(status_flags::dynallocated);
541 /** Implementation of ex::expand() for a power series. It expands all the
542 * terms individually and returns the resulting series as a new pseries. */
543 ex pseries::expand(unsigned options) const
546 epvector::const_iterator i = seq.begin(), end = seq.end();
548 ex restexp = i->rest.expand();
549 if (!restexp.is_zero())
550 newseq.push_back(expair(restexp, i->coeff));
553 return (new pseries(relational(var,point), newseq))
554 ->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
557 /** Implementation of ex::diff() for a power series.
559 ex pseries::derivative(const symbol & s) const
562 epvector::const_iterator it = seq.begin(), itend = seq.end();
566 // FIXME: coeff might depend on var
567 while (it != itend) {
568 if (is_order_function(it->rest)) {
569 new_seq.push_back(expair(it->rest, it->coeff - 1));
571 ex c = it->rest * it->coeff;
573 new_seq.push_back(expair(c, it->coeff - 1));
580 while (it != itend) {
581 if (is_order_function(it->rest)) {
582 new_seq.push_back(*it);
584 ex c = it->rest.diff(s);
586 new_seq.push_back(expair(c, it->coeff));
592 return pseries(relational(var,point), new_seq);
595 ex pseries::convert_to_poly(bool no_order) const
598 epvector::const_iterator it = seq.begin(), itend = seq.end();
600 while (it != itend) {
601 if (is_order_function(it->rest)) {
603 e += Order(power(var - point, it->coeff));
605 e += it->rest * power(var - point, it->coeff);
611 bool pseries::is_terminating() const
613 return seq.empty() || !is_order_function((seq.end()-1)->rest);
616 ex pseries::coeffop(size_t i) const
619 throw (std::out_of_range("coeffop() out of range"));
623 ex pseries::exponop(size_t i) const
626 throw (std::out_of_range("exponop() out of range"));
632 * Implementations of series expansion
635 /** Default implementation of ex::series(). This performs Taylor expansion.
637 ex basic::series(const relational & r, int order, unsigned options) const
640 const symbol &s = ex_to<symbol>(r.lhs());
642 // default for order-values that make no sense for Taylor expansion
643 if ((order <= 0) && this->has(s)) {
644 seq.push_back(expair(Order(_ex1), order));
645 return pseries(r, seq);
648 // do Taylor expansion
651 ex coeff = deriv.subs(r, subs_options::no_pattern);
653 if (!coeff.is_zero()) {
654 seq.push_back(expair(coeff, _ex0));
658 for (n=1; n<order; ++n) {
660 // We need to test for zero in order to see if the series terminates.
661 // The problem is that there is no such thing as a perfect test for
662 // zero. Expanding the term occasionally helps a little...
663 deriv = deriv.diff(s).expand();
664 if (deriv.is_zero()) // Series terminates
665 return pseries(r, seq);
667 coeff = deriv.subs(r, subs_options::no_pattern);
668 if (!coeff.is_zero())
669 seq.push_back(expair(fac.inverse() * coeff, n));
672 // Higher-order terms, if present
673 deriv = deriv.diff(s);
674 if (!deriv.expand().is_zero())
675 seq.push_back(expair(Order(_ex1), n));
676 return pseries(r, seq);
680 /** Implementation of ex::series() for symbols.
682 ex symbol::series(const relational & r, int order, unsigned options) const
685 const ex point = r.rhs();
686 GINAC_ASSERT(is_a<symbol>(r.lhs()));
688 if (this->is_equal_same_type(ex_to<symbol>(r.lhs()))) {
689 if (order > 0 && !point.is_zero())
690 seq.push_back(expair(point, _ex0));
692 seq.push_back(expair(_ex1, _ex1));
694 seq.push_back(expair(Order(_ex1), numeric(order)));
696 seq.push_back(expair(*this, _ex0));
697 return pseries(r, seq);
701 /** Add one series object to another, producing a pseries object that
702 * represents the sum.
704 * @param other pseries object to add with
705 * @return the sum as a pseries */
706 ex pseries::add_series(const pseries &other) const
708 // Adding two series with different variables or expansion points
709 // results in an empty (constant) series
710 if (!is_compatible_to(other)) {
712 nul.push_back(expair(Order(_ex1), _ex0));
713 return pseries(relational(var,point), nul);
718 epvector::const_iterator a = seq.begin();
719 epvector::const_iterator b = other.seq.begin();
720 epvector::const_iterator a_end = seq.end();
721 epvector::const_iterator b_end = other.seq.end();
722 int pow_a = std::numeric_limits<int>::max(), pow_b = std::numeric_limits<int>::max();
724 // If a is empty, fill up with elements from b and stop
727 new_seq.push_back(*b);
732 pow_a = ex_to<numeric>((*a).coeff).to_int();
734 // If b is empty, fill up with elements from a and stop
737 new_seq.push_back(*a);
742 pow_b = ex_to<numeric>((*b).coeff).to_int();
744 // a and b are non-empty, compare powers
746 // a has lesser power, get coefficient from a
747 new_seq.push_back(*a);
748 if (is_order_function((*a).rest))
751 } else if (pow_b < pow_a) {
752 // b has lesser power, get coefficient from b
753 new_seq.push_back(*b);
754 if (is_order_function((*b).rest))
758 // Add coefficient of a and b
759 if (is_order_function((*a).rest) || is_order_function((*b).rest)) {
760 new_seq.push_back(expair(Order(_ex1), (*a).coeff));
761 break; // Order term ends the sequence
763 ex sum = (*a).rest + (*b).rest;
764 if (!(sum.is_zero()))
765 new_seq.push_back(expair(sum, numeric(pow_a)));
771 return pseries(relational(var,point), new_seq);
775 /** Implementation of ex::series() for sums. This performs series addition when
776 * adding pseries objects.
778 ex add::series(const relational & r, int order, unsigned options) const
780 ex acc; // Series accumulator
782 // Get first term from overall_coeff
783 acc = overall_coeff.series(r, order, options);
785 // Add remaining terms
786 epvector::const_iterator it = seq.begin();
787 epvector::const_iterator itend = seq.end();
788 for (; it!=itend; ++it) {
790 if (is_exactly_a<pseries>(it->rest))
793 op = it->rest.series(r, order, options);
794 if (!it->coeff.is_equal(_ex1))
795 op = ex_to<pseries>(op).mul_const(ex_to<numeric>(it->coeff));
798 acc = ex_to<pseries>(acc).add_series(ex_to<pseries>(op));
804 /** Multiply a pseries object with a numeric constant, producing a pseries
805 * object that represents the product.
807 * @param other constant to multiply with
808 * @return the product as a pseries */
809 ex pseries::mul_const(const numeric &other) const
812 new_seq.reserve(seq.size());
814 epvector::const_iterator it = seq.begin(), itend = seq.end();
815 while (it != itend) {
816 if (!is_order_function(it->rest))
817 new_seq.push_back(expair(it->rest * other, it->coeff));
819 new_seq.push_back(*it);
822 return pseries(relational(var,point), new_seq);
826 /** Multiply one pseries object to another, producing a pseries object that
827 * represents the product.
829 * @param other pseries object to multiply with
830 * @return the product as a pseries */
831 ex pseries::mul_series(const pseries &other) const
833 // Multiplying two series with different variables or expansion points
834 // results in an empty (constant) series
835 if (!is_compatible_to(other)) {
837 nul.push_back(expair(Order(_ex1), _ex0));
838 return pseries(relational(var,point), nul);
841 if (seq.empty() || other.seq.empty()) {
842 return (new pseries(var==point, epvector()))
843 ->setflag(status_flags::dynallocated);
846 // Series multiplication
848 int a_max = degree(var);
849 int b_max = other.degree(var);
850 int a_min = ldegree(var);
851 int b_min = other.ldegree(var);
852 int cdeg_min = a_min + b_min;
853 int cdeg_max = a_max + b_max;
855 int higher_order_a = std::numeric_limits<int>::max();
856 int higher_order_b = std::numeric_limits<int>::max();
857 if (is_order_function(coeff(var, a_max)))
858 higher_order_a = a_max + b_min;
859 if (is_order_function(other.coeff(var, b_max)))
860 higher_order_b = b_max + a_min;
861 int higher_order_c = std::min(higher_order_a, higher_order_b);
862 if (cdeg_max >= higher_order_c)
863 cdeg_max = higher_order_c - 1;
865 for (int cdeg=cdeg_min; cdeg<=cdeg_max; ++cdeg) {
867 // c(i)=a(0)b(i)+...+a(i)b(0)
868 for (int i=a_min; cdeg-i>=b_min; ++i) {
869 ex a_coeff = coeff(var, i);
870 ex b_coeff = other.coeff(var, cdeg-i);
871 if (!is_order_function(a_coeff) && !is_order_function(b_coeff))
872 co += a_coeff * b_coeff;
875 new_seq.push_back(expair(co, numeric(cdeg)));
877 if (higher_order_c < std::numeric_limits<int>::max())
878 new_seq.push_back(expair(Order(_ex1), numeric(higher_order_c)));
879 return pseries(relational(var, point), new_seq);
883 /** Implementation of ex::series() for product. This performs series
884 * multiplication when multiplying series.
886 ex mul::series(const relational & r, int order, unsigned options) const
888 pseries acc; // Series accumulator
890 GINAC_ASSERT(is_a<symbol>(r.lhs()));
891 const ex& sym = r.lhs();
893 // holds ldegrees of the series of individual factors
894 std::vector<int> ldegrees;
895 std::vector<bool> ldegree_redo;
897 // find minimal degrees
898 const epvector::const_iterator itbeg = seq.begin();
899 const epvector::const_iterator itend = seq.end();
900 // first round: obtain a bound up to which minimal degrees have to be
902 for (epvector::const_iterator it=itbeg; it!=itend; ++it) {
904 ex expon = it->coeff;
907 if (expon.info(info_flags::integer)) {
909 factor = ex_to<numeric>(expon).to_int();
911 buf = recombine_pair_to_ex(*it);
914 int real_ldegree = 0;
915 bool flag_redo = false;
917 real_ldegree = buf.expand().ldegree(sym-r.rhs());
918 } catch (std::runtime_error) {}
920 if (real_ldegree == 0) {
922 // This case must terminate, otherwise we would have division by
927 real_ldegree = buf.series(r, orderloop, options).ldegree(sym);
928 } while (real_ldegree == orderloop);
930 // Here it is possible that buf does not have a ldegree, therefore
931 // check only if ldegree is negative, otherwise reconsider the case
932 // in the second round.
933 real_ldegree = buf.series(r, 0, options).ldegree(sym);
934 if (real_ldegree == 0)
939 ldegrees.push_back(factor * real_ldegree);
940 ldegree_redo.push_back(flag_redo);
943 int degbound = order-std::accumulate(ldegrees.begin(), ldegrees.end(), 0);
944 // Second round: determine the remaining positive ldegrees by the series
946 // here we can ignore ldegrees larger than degbound
948 for (epvector::const_iterator it=itbeg; it!=itend; ++it) {
949 if ( ldegree_redo[j] ) {
950 ex expon = it->coeff;
953 if (expon.info(info_flags::integer)) {
955 factor = ex_to<numeric>(expon).to_int();
957 buf = recombine_pair_to_ex(*it);
959 int real_ldegree = 0;
963 real_ldegree = buf.series(r, orderloop, options).ldegree(sym);
964 } while ((real_ldegree == orderloop)
965 && ( factor*real_ldegree < degbound));
966 ldegrees[j] = factor * real_ldegree;
967 degbound -= factor * real_ldegree;
972 int degsum = std::accumulate(ldegrees.begin(), ldegrees.end(), 0);
974 if (degsum >= order) {
976 epv.push_back(expair(Order(_ex1), order));
977 return (new pseries(r, epv))->setflag(status_flags::dynallocated);
980 // Multiply with remaining terms
981 std::vector<int>::const_iterator itd = ldegrees.begin();
982 for (epvector::const_iterator it=itbeg; it!=itend; ++it, ++itd) {
984 // do series expansion with adjusted order
985 ex op = recombine_pair_to_ex(*it).series(r, order-degsum+(*itd), options);
987 // Series multiplication
989 acc = ex_to<pseries>(op);
991 acc = ex_to<pseries>(acc.mul_series(ex_to<pseries>(op)));
994 return acc.mul_const(ex_to<numeric>(overall_coeff));
998 /** Compute the p-th power of a series.
1000 * @param p power to compute
1001 * @param deg truncation order of series calculation */
1002 ex pseries::power_const(const numeric &p, int deg) const
1005 // (due to Leonhard Euler)
1006 // let A(x) be this series and for the time being let it start with a
1007 // constant (later we'll generalize):
1008 // A(x) = a_0 + a_1*x + a_2*x^2 + ...
1009 // We want to compute
1011 // C(x) = c_0 + c_1*x + c_2*x^2 + ...
1012 // Taking the derivative on both sides and multiplying with A(x) one
1013 // immediately arrives at
1014 // C'(x)*A(x) = p*C(x)*A'(x)
1015 // Multiplying this out and comparing coefficients we get the recurrence
1017 // c_i = (i*p*a_i*c_0 + ((i-1)*p-1)*a_{i-1}*c_1 + ...
1018 // ... + (p-(i-1))*a_1*c_{i-1})/(a_0*i)
1019 // which can easily be solved given the starting value c_0 = (a_0)^p.
1020 // For the more general case where the leading coefficient of A(x) is not
1021 // a constant, just consider A2(x) = A(x)*x^m, with some integer m and
1022 // repeat the above derivation. The leading power of C2(x) = A2(x)^2 is
1023 // then of course x^(p*m) but the recurrence formula still holds.
1026 // as a special case, handle the empty (zero) series honoring the
1027 // usual power laws such as implemented in power::eval()
1028 if (p.real().is_zero())
1029 throw std::domain_error("pseries::power_const(): pow(0,I) is undefined");
1030 else if (p.real().is_negative())
1031 throw pole_error("pseries::power_const(): division by zero",1);
1036 const int ldeg = ldegree(var);
1037 if (!(p*ldeg).is_integer())
1038 throw std::runtime_error("pseries::power_const(): trying to assemble a Puiseux series");
1040 // adjust number of coefficients
1041 int numcoeff = deg - (p*ldeg).to_int();
1042 if (numcoeff <= 0) {
1045 epv.push_back(expair(Order(_ex1), deg));
1046 return (new pseries(relational(var,point), epv))
1047 ->setflag(status_flags::dynallocated);
1050 // O(x^n)^(-m) is undefined
1051 if (seq.size() == 1 && is_order_function(seq[0].rest) && p.real().is_negative())
1052 throw pole_error("pseries::power_const(): division by zero",1);
1054 // Compute coefficients of the powered series
1056 co.reserve(numcoeff);
1057 co.push_back(power(coeff(var, ldeg), p));
1058 for (int i=1; i<numcoeff; ++i) {
1060 for (int j=1; j<=i; ++j) {
1061 ex c = coeff(var, j + ldeg);
1062 if (is_order_function(c)) {
1063 co.push_back(Order(_ex1));
1066 sum += (p * j - (i - j)) * co[i - j] * c;
1068 co.push_back(sum / coeff(var, ldeg) / i);
1071 // Construct new series (of non-zero coefficients)
1073 bool higher_order = false;
1074 for (int i=0; i<numcoeff; ++i) {
1075 if (!co[i].is_zero())
1076 new_seq.push_back(expair(co[i], p * ldeg + i));
1077 if (is_order_function(co[i])) {
1078 higher_order = true;
1083 new_seq.push_back(expair(Order(_ex1), p * ldeg + numcoeff));
1085 return pseries(relational(var,point), new_seq);
1089 /** Return a new pseries object with the powers shifted by deg. */
1090 pseries pseries::shift_exponents(int deg) const
1092 epvector newseq = seq;
1093 epvector::iterator i = newseq.begin(), end = newseq.end();
1098 return pseries(relational(var, point), newseq);
1102 /** Implementation of ex::series() for powers. This performs Laurent expansion
1103 * of reciprocals of series at singularities.
1104 * @see ex::series */
1105 ex power::series(const relational & r, int order, unsigned options) const
1107 // If basis is already a series, just power it
1108 if (is_exactly_a<pseries>(basis))
1109 return ex_to<pseries>(basis).power_const(ex_to<numeric>(exponent), order);
1111 // Basis is not a series, may there be a singularity?
1112 bool must_expand_basis = false;
1114 basis.subs(r, subs_options::no_pattern);
1115 } catch (pole_error) {
1116 must_expand_basis = true;
1119 // Is the expression of type something^(-int)?
1120 if (!must_expand_basis && !exponent.info(info_flags::negint)
1121 && (!is_a<add>(basis) || !is_a<numeric>(exponent)))
1122 return basic::series(r, order, options);
1124 // Is the expression of type 0^something?
1125 if (!must_expand_basis && !basis.subs(r, subs_options::no_pattern).is_zero()
1126 && (!is_a<add>(basis) || !is_a<numeric>(exponent)))
1127 return basic::series(r, order, options);
1129 // Singularity encountered, is the basis equal to (var - point)?
1130 if (basis.is_equal(r.lhs() - r.rhs())) {
1132 if (ex_to<numeric>(exponent).to_int() < order)
1133 new_seq.push_back(expair(_ex1, exponent));
1135 new_seq.push_back(expair(Order(_ex1), exponent));
1136 return pseries(r, new_seq);
1139 // No, expand basis into series
1142 if (is_a<numeric>(exponent)) {
1143 numexp = ex_to<numeric>(exponent);
1147 const ex& sym = r.lhs();
1148 // find existing minimal degree
1149 ex eb = basis.expand();
1150 int real_ldegree = 0;
1151 if (eb.info(info_flags::rational_function))
1152 real_ldegree = eb.ldegree(sym-r.rhs());
1153 if (real_ldegree == 0) {
1157 real_ldegree = basis.series(r, orderloop, options).ldegree(sym);
1158 } while (real_ldegree == orderloop);
1161 if (!(real_ldegree*numexp).is_integer())
1162 throw std::runtime_error("pseries::power_const(): trying to assemble a Puiseux series");
1163 ex e = basis.series(r, (order + real_ldegree*(1-numexp)).to_int(), options);
1167 result = ex_to<pseries>(e).power_const(numexp, order);
1168 } catch (pole_error) {
1170 ser.push_back(expair(Order(_ex1), order));
1171 result = pseries(r, ser);
1178 /** Re-expansion of a pseries object. */
1179 ex pseries::series(const relational & r, int order, unsigned options) const
1181 const ex p = r.rhs();
1182 GINAC_ASSERT(is_a<symbol>(r.lhs()));
1183 const symbol &s = ex_to<symbol>(r.lhs());
1185 if (var.is_equal(s) && point.is_equal(p)) {
1186 if (order > degree(s))
1190 epvector::const_iterator it = seq.begin(), itend = seq.end();
1191 while (it != itend) {
1192 int o = ex_to<numeric>(it->coeff).to_int();
1194 new_seq.push_back(expair(Order(_ex1), o));
1197 new_seq.push_back(*it);
1200 return pseries(r, new_seq);
1203 return convert_to_poly().series(r, order, options);
1206 ex integral::series(const relational & r, int order, unsigned options) const
1209 throw std::logic_error("Cannot series expand wrt dummy variable");
1211 // Expanding integrant with r substituted taken in boundaries.
1212 ex fseries = f.series(r, order, options);
1213 epvector fexpansion;
1214 fexpansion.reserve(fseries.nops());
1215 for (size_t i=0; i<fseries.nops(); ++i) {
1216 ex currcoeff = ex_to<pseries>(fseries).coeffop(i);
1217 currcoeff = (currcoeff == Order(_ex1))
1219 : integral(x, a.subs(r), b.subs(r), currcoeff);
1221 fexpansion.push_back(
1222 expair(currcoeff, ex_to<pseries>(fseries).exponop(i)));
1225 // Expanding lower boundary
1226 ex result = (new pseries(r, fexpansion))->setflag(status_flags::dynallocated);
1227 ex aseries = (a-a.subs(r)).series(r, order, options);
1228 fseries = f.series(x == (a.subs(r)), order, options);
1229 for (size_t i=0; i<fseries.nops(); ++i) {
1230 ex currcoeff = ex_to<pseries>(fseries).coeffop(i);
1231 if (is_order_function(currcoeff))
1233 ex currexpon = ex_to<pseries>(fseries).exponop(i);
1234 int orderforf = order-ex_to<numeric>(currexpon).to_int()-1;
1235 currcoeff = currcoeff.series(r, orderforf);
1236 ex term = ex_to<pseries>(aseries).power_const(ex_to<numeric>(currexpon+1),order);
1237 term = ex_to<pseries>(term).mul_const(ex_to<numeric>(-1/(currexpon+1)));
1238 term = ex_to<pseries>(term).mul_series(ex_to<pseries>(currcoeff));
1239 result = ex_to<pseries>(result).add_series(ex_to<pseries>(term));
1242 // Expanding upper boundary
1243 ex bseries = (b-b.subs(r)).series(r, order, options);
1244 fseries = f.series(x == (b.subs(r)), order, options);
1245 for (size_t i=0; i<fseries.nops(); ++i) {
1246 ex currcoeff = ex_to<pseries>(fseries).coeffop(i);
1247 if (is_order_function(currcoeff))
1249 ex currexpon = ex_to<pseries>(fseries).exponop(i);
1250 int orderforf = order-ex_to<numeric>(currexpon).to_int()-1;
1251 currcoeff = currcoeff.series(r, orderforf);
1252 ex term = ex_to<pseries>(bseries).power_const(ex_to<numeric>(currexpon+1),order);
1253 term = ex_to<pseries>(term).mul_const(ex_to<numeric>(1/(currexpon+1)));
1254 term = ex_to<pseries>(term).mul_series(ex_to<pseries>(currcoeff));
1255 result = ex_to<pseries>(result).add_series(ex_to<pseries>(term));
1262 /** Compute the truncated series expansion of an expression.
1263 * This function returns an expression containing an object of class pseries
1264 * to represent the series. If the series does not terminate within the given
1265 * truncation order, the last term of the series will be an order term.
1267 * @param r expansion relation, lhs holds variable and rhs holds point
1268 * @param order truncation order of series calculations
1269 * @param options of class series_options
1270 * @return an expression holding a pseries object */
1271 ex ex::series(const ex & r, int order, unsigned options) const
1276 if (is_a<relational>(r))
1277 rel_ = ex_to<relational>(r);
1278 else if (is_a<symbol>(r))
1279 rel_ = relational(r,_ex0);
1281 throw (std::logic_error("ex::series(): expansion point has unknown type"));
1284 e = bp->series(rel_, order, options);
1285 } catch (std::exception &x) {
1286 throw (std::logic_error(std::string("unable to compute series (") + x.what() + ")"));
1291 } // namespace GiNaC