3 * Implementation of class for extended truncated power series and
4 * methods for series expansion. */
7 * GiNaC Copyright (C) 1999-2000 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
32 #include "relational.h"
38 #ifndef NO_NAMESPACE_GINAC
40 #endif // ndef NO_NAMESPACE_GINAC
42 GINAC_IMPLEMENT_REGISTERED_CLASS(pseries, basic)
45 * Default constructor, destructor, copy constructor, assignment operator and helpers
48 pseries::pseries() : basic(TINFO_pseries)
50 debugmsg("pseries default constructor", LOGLEVEL_CONSTRUCT);
55 debugmsg("pseries destructor", LOGLEVEL_DESTRUCT);
59 pseries::pseries(const pseries &other)
61 debugmsg("pseries copy constructor", LOGLEVEL_CONSTRUCT);
65 const pseries &pseries::operator=(const pseries & other)
67 debugmsg("pseries operator=", LOGLEVEL_ASSIGNMENT);
75 void pseries::copy(const pseries &other)
77 inherited::copy(other);
83 void pseries::destroy(bool call_parent)
86 inherited::destroy(call_parent);
94 /** Construct pseries from a vector of coefficients and powers.
95 * expair.rest holds the coefficient, expair.coeff holds the power.
96 * The powers must be integers (positive or negative) and in ascending order;
97 * the last coefficient can be Order(_ex1()) to represent a truncated,
98 * non-terminating series.
100 * @param rel__ expansion variable and point (must hold a relational)
101 * @param ops_ vector of {coefficient, power} pairs (coefficient must not be zero)
102 * @return newly constructed pseries */
103 pseries::pseries(const ex &rel_, const epvector &ops_)
104 : basic(TINFO_pseries), seq(ops_)
106 debugmsg("pseries constructor from rel,epvector", LOGLEVEL_CONSTRUCT);
107 GINAC_ASSERT(is_ex_exactly_of_type(rel_, relational));
108 GINAC_ASSERT(is_ex_exactly_of_type(rel_.lhs(),symbol));
110 var = *static_cast<symbol *>(rel_.lhs().bp);
118 /** Construct object from archive_node. */
119 pseries::pseries(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
121 debugmsg("pseries constructor from archive_node", LOGLEVEL_CONSTRUCT);
122 for (unsigned int i=0; true; i++) {
125 if (n.find_ex("coeff", rest, sym_lst, i) && n.find_ex("power", coeff, sym_lst, i))
126 seq.push_back(expair(rest, coeff));
130 n.find_ex("var", var, sym_lst);
131 n.find_ex("point", point, sym_lst);
134 /** Unarchive the object. */
135 ex pseries::unarchive(const archive_node &n, const lst &sym_lst)
137 return (new pseries(n, sym_lst))->setflag(status_flags::dynallocated);
140 /** Archive the object. */
141 void pseries::archive(archive_node &n) const
143 inherited::archive(n);
144 epvector::const_iterator i = seq.begin(), iend = seq.end();
146 n.add_ex("coeff", i->rest);
147 n.add_ex("power", i->coeff);
150 n.add_ex("var", var);
151 n.add_ex("point", point);
155 // functions overriding virtual functions from bases classes
158 basic *pseries::duplicate() const
160 debugmsg("pseries duplicate", LOGLEVEL_DUPLICATE);
161 return new pseries(*this);
164 void pseries::print(ostream &os, unsigned upper_precedence) const
166 debugmsg("pseries print", LOGLEVEL_PRINT);
167 for (epvector::const_iterator i=seq.begin(); i!=seq.end(); i++) {
168 // print a sign, if needed
171 if (!is_order_function(i->rest)) {
172 // print 'rest', i.e. the expansion coefficient
173 if (i->rest.info(info_flags::numeric) &&
174 i->rest.info(info_flags::positive)) {
177 os << "(" << i->rest << ')';
178 // print 'coeff', something like (x-1)^42
179 if (!i->coeff.is_zero()) {
181 if (!point.is_zero())
182 os << '(' << var-point << ')';
185 if (i->coeff.compare(_ex1())) {
187 if (i->coeff.info(info_flags::negative))
188 os << '(' << i->coeff << ')';
194 os << Order(power(var-point,i->coeff));
199 void pseries::printraw(ostream &os) const
201 debugmsg("pseries printraw", LOGLEVEL_PRINT);
202 os << "pseries(" << var << ";" << point << ";";
203 for (epvector::const_iterator i=seq.begin(); i!=seq.end(); i++) {
204 os << "(" << (*i).rest << "," << (*i).coeff << "),";
209 void pseries::printtree(ostream & os, unsigned indent) const
211 debugmsg("pseries printtree",LOGLEVEL_PRINT);
212 os << string(indent,' ') << "pseries "
213 << ", hash=" << hashvalue << " (0x" << hex << hashvalue << dec << ")"
214 << ", flags=" << flags << endl;
215 for (unsigned i=0; i<seq.size(); ++i) {
216 seq[i].rest.printtree(os,indent+delta_indent);
217 seq[i].coeff.printtree(os,indent+delta_indent);
218 if (i!=seq.size()-1) {
219 os << string(indent+delta_indent,' ') << "-----" << endl;
222 var.printtree(os, indent+delta_indent);
223 point.printtree(os, indent+delta_indent);
226 unsigned pseries::nops(void) const
231 ex pseries::op(int i) const
233 if (i < 0 || unsigned(i) >= seq.size())
234 throw (std::out_of_range("op() out of range"));
235 return seq[i].rest * power(var - point, seq[i].coeff);
238 ex &pseries::let_op(int i)
240 throw (std::logic_error("let_op not defined for pseries"));
243 int pseries::degree(const symbol &s) const
245 if (var.is_equal(s)) {
246 // Return last exponent
248 return ex_to_numeric((*(seq.end() - 1)).coeff).to_int();
252 epvector::const_iterator it = seq.begin(), itend = seq.end();
255 int max_pow = INT_MIN;
256 while (it != itend) {
257 int pow = it->rest.degree(s);
266 int pseries::ldegree(const symbol &s) const
268 if (var.is_equal(s)) {
269 // Return first exponent
271 return ex_to_numeric((*(seq.begin())).coeff).to_int();
275 epvector::const_iterator it = seq.begin(), itend = seq.end();
278 int min_pow = INT_MAX;
279 while (it != itend) {
280 int pow = it->rest.ldegree(s);
289 ex pseries::coeff(const symbol &s, int n) const
291 if (var.is_equal(s)) {
295 // Binary search in sequence for given power
296 numeric looking_for = numeric(n);
297 int lo = 0, hi = seq.size() - 1;
299 int mid = (lo + hi) / 2;
300 GINAC_ASSERT(is_ex_exactly_of_type(seq[mid].coeff, numeric));
301 int cmp = ex_to_numeric(seq[mid].coeff).compare(looking_for);
307 return seq[mid].rest;
312 throw(std::logic_error("pseries::coeff: compare() didn't return -1, 0 or 1"));
317 return convert_to_poly().coeff(s, n);
320 ex pseries::collect(const symbol &s) const
325 /** Evaluate coefficients. */
326 ex pseries::eval(int level) const
331 if (level == -max_recursion_level)
332 throw (std::runtime_error("pseries::eval(): recursion limit exceeded"));
334 // Construct a new series with evaluated coefficients
336 new_seq.reserve(seq.size());
337 epvector::const_iterator it = seq.begin(), itend = seq.end();
338 while (it != itend) {
339 new_seq.push_back(expair(it->rest.eval(level-1), it->coeff));
342 return (new pseries(relational(var,point), new_seq))->setflag(status_flags::dynallocated | status_flags::evaluated);
345 /** Evaluate coefficients numerically. */
346 ex pseries::evalf(int level) const
351 if (level == -max_recursion_level)
352 throw (std::runtime_error("pseries::evalf(): recursion limit exceeded"));
354 // Construct a new series with evaluated coefficients
356 new_seq.reserve(seq.size());
357 epvector::const_iterator it = seq.begin(), itend = seq.end();
358 while (it != itend) {
359 new_seq.push_back(expair(it->rest.evalf(level-1), it->coeff));
362 return (new pseries(relational(var,point), new_seq))->setflag(status_flags::dynallocated | status_flags::evaluated);
365 ex pseries::subs(const lst & ls, const lst & lr) const
367 // If expansion variable is being substituted, convert the series to a
368 // polynomial and do the substitution there because the result might
369 // no longer be a power series
371 return convert_to_poly(true).subs(ls, lr);
373 // Otherwise construct a new series with substituted coefficients and
376 new_seq.reserve(seq.size());
377 epvector::const_iterator it = seq.begin(), itend = seq.end();
378 while (it != itend) {
379 new_seq.push_back(expair(it->rest.subs(ls, lr), it->coeff));
382 return (new pseries(relational(var,point.subs(ls, lr)), new_seq))->setflag(status_flags::dynallocated);
385 /** Implementation of ex::diff() for a power series. It treats the series as a
388 ex pseries::derivative(const symbol & s) const
392 epvector::const_iterator it = seq.begin(), itend = seq.end();
394 // FIXME: coeff might depend on var
395 while (it != itend) {
396 if (is_order_function(it->rest)) {
397 new_seq.push_back(expair(it->rest, it->coeff - 1));
399 ex c = it->rest * it->coeff;
401 new_seq.push_back(expair(c, it->coeff - 1));
405 return pseries(relational(var,point), new_seq);
413 * Construct ordinary polynomial out of series
416 /** Convert a pseries object to an ordinary polynomial.
418 * @param no_order flag: discard higher order terms */
419 ex pseries::convert_to_poly(bool no_order) const
422 epvector::const_iterator it = seq.begin(), itend = seq.end();
424 while (it != itend) {
425 if (is_order_function(it->rest)) {
427 e += Order(power(var - point, it->coeff));
429 e += it->rest * power(var - point, it->coeff);
437 * Implementation of series expansion
440 /** Default implementation of ex::series(). This performs Taylor expansion.
442 ex basic::series(const relational & r, int order) const
447 ex coeff = deriv.subs(r);
448 const symbol *s = static_cast<symbol *>(r.lhs().bp);
450 if (!coeff.is_zero())
451 seq.push_back(expair(coeff, numeric(0)));
454 for (n=1; n<order; n++) {
455 fac = fac.mul(numeric(n));
456 deriv = deriv.diff(*s).expand();
457 if (deriv.is_zero()) {
459 return pseries(r, seq);
461 coeff = fac.inverse() * deriv.subs(r);
462 if (!coeff.is_zero())
463 seq.push_back(expair(coeff, numeric(n)));
466 // Higher-order terms, if present
467 deriv = deriv.diff(*s);
468 if (!deriv.is_zero())
469 seq.push_back(expair(Order(_ex1()), numeric(n)));
470 return pseries(r, seq);
474 /** Implementation of ex::series() for symbols.
476 ex symbol::series(const relational & r, int order) const
479 const ex point = r.rhs();
480 GINAC_ASSERT(is_ex_exactly_of_type(r.lhs(),symbol));
481 const symbol *s = static_cast<symbol *>(r.lhs().bp);
483 if (this->is_equal(*s)) {
484 if (order > 0 && !point.is_zero())
485 seq.push_back(expair(point, _ex0()));
487 seq.push_back(expair(_ex1(), _ex1()));
489 seq.push_back(expair(Order(_ex1()), numeric(order)));
491 seq.push_back(expair(*this, _ex0()));
492 return pseries(r, seq);
496 /** Add one series object to another, producing a pseries object that
497 * represents the sum.
499 * @param other pseries object to add with
500 * @return the sum as a pseries */
501 ex pseries::add_series(const pseries &other) const
503 // Adding two series with different variables or expansion points
504 // results in an empty (constant) series
505 if (!is_compatible_to(other)) {
507 nul.push_back(expair(Order(_ex1()), _ex0()));
508 return pseries(relational(var,point), nul);
513 epvector::const_iterator a = seq.begin();
514 epvector::const_iterator b = other.seq.begin();
515 epvector::const_iterator a_end = seq.end();
516 epvector::const_iterator b_end = other.seq.end();
517 int pow_a = INT_MAX, pow_b = INT_MAX;
519 // If a is empty, fill up with elements from b and stop
522 new_seq.push_back(*b);
527 pow_a = ex_to_numeric((*a).coeff).to_int();
529 // If b is empty, fill up with elements from a and stop
532 new_seq.push_back(*a);
537 pow_b = ex_to_numeric((*b).coeff).to_int();
539 // a and b are non-empty, compare powers
541 // a has lesser power, get coefficient from a
542 new_seq.push_back(*a);
543 if (is_order_function((*a).rest))
546 } else if (pow_b < pow_a) {
547 // b has lesser power, get coefficient from b
548 new_seq.push_back(*b);
549 if (is_order_function((*b).rest))
553 // Add coefficient of a and b
554 if (is_order_function((*a).rest) || is_order_function((*b).rest)) {
555 new_seq.push_back(expair(Order(_ex1()), (*a).coeff));
556 break; // Order term ends the sequence
558 ex sum = (*a).rest + (*b).rest;
559 if (!(sum.is_zero()))
560 new_seq.push_back(expair(sum, numeric(pow_a)));
566 return pseries(relational(var,point), new_seq);
570 /** Implementation of ex::series() for sums. This performs series addition when
571 * adding pseries objects.
573 ex add::series(const relational & r, int order) const
575 ex acc; // Series accumulator
577 // Get first term from overall_coeff
578 acc = overall_coeff.series(r, order);
580 // Add remaining terms
581 epvector::const_iterator it = seq.begin();
582 epvector::const_iterator itend = seq.end();
583 for (; it!=itend; it++) {
585 if (is_ex_exactly_of_type(it->rest, pseries))
588 op = it->rest.series(r, order);
589 if (!it->coeff.is_equal(_ex1()))
590 op = ex_to_pseries(op).mul_const(ex_to_numeric(it->coeff));
593 acc = ex_to_pseries(acc).add_series(ex_to_pseries(op));
599 /** Multiply a pseries object with a numeric constant, producing a pseries
600 * object that represents the product.
602 * @param other constant to multiply with
603 * @return the product as a pseries */
604 ex pseries::mul_const(const numeric &other) const
607 new_seq.reserve(seq.size());
609 epvector::const_iterator it = seq.begin(), itend = seq.end();
610 while (it != itend) {
611 if (!is_order_function(it->rest))
612 new_seq.push_back(expair(it->rest * other, it->coeff));
614 new_seq.push_back(*it);
617 return pseries(relational(var,point), new_seq);
621 /** Multiply one pseries object to another, producing a pseries object that
622 * represents the product.
624 * @param other pseries object to multiply with
625 * @return the product as a pseries */
626 ex pseries::mul_series(const pseries &other) const
628 // Multiplying two series with different variables or expansion points
629 // results in an empty (constant) series
630 if (!is_compatible_to(other)) {
632 nul.push_back(expair(Order(_ex1()), _ex0()));
633 return pseries(relational(var,point), nul);
636 // Series multiplication
639 const symbol *s = static_cast<symbol *>(var.bp);
640 int a_max = degree(*s);
641 int b_max = other.degree(*s);
642 int a_min = ldegree(*s);
643 int b_min = other.ldegree(*s);
644 int cdeg_min = a_min + b_min;
645 int cdeg_max = a_max + b_max;
647 int higher_order_a = INT_MAX;
648 int higher_order_b = INT_MAX;
649 if (is_order_function(coeff(*s, a_max)))
650 higher_order_a = a_max + b_min;
651 if (is_order_function(other.coeff(*s, b_max)))
652 higher_order_b = b_max + a_min;
653 int higher_order_c = min(higher_order_a, higher_order_b);
654 if (cdeg_max >= higher_order_c)
655 cdeg_max = higher_order_c - 1;
657 for (int cdeg=cdeg_min; cdeg<=cdeg_max; cdeg++) {
659 // c(i)=a(0)b(i)+...+a(i)b(0)
660 for (int i=a_min; cdeg-i>=b_min; i++) {
661 ex a_coeff = coeff(*s, i);
662 ex b_coeff = other.coeff(*s, cdeg-i);
663 if (!is_order_function(a_coeff) && !is_order_function(b_coeff))
664 co += a_coeff * b_coeff;
667 new_seq.push_back(expair(co, numeric(cdeg)));
669 if (higher_order_c < INT_MAX)
670 new_seq.push_back(expair(Order(_ex1()), numeric(higher_order_c)));
671 return pseries(relational(var,point), new_seq);
675 /** Implementation of ex::series() for product. This performs series
676 * multiplication when multiplying series.
678 ex mul::series(const relational & r, int order) const
680 ex acc; // Series accumulator
682 // Get first term from overall_coeff
683 acc = overall_coeff.series(r, order);
685 // Multiply with remaining terms
686 epvector::const_iterator it = seq.begin();
687 epvector::const_iterator itend = seq.end();
688 for (; it!=itend; it++) {
690 if (op.info(info_flags::numeric)) {
691 // series * const (special case, faster)
692 ex f = power(op, it->coeff);
693 acc = ex_to_pseries(acc).mul_const(ex_to_numeric(f));
695 } else if (!is_ex_exactly_of_type(op, pseries))
696 op = op.series(r, order);
697 if (!it->coeff.is_equal(_ex1()))
698 op = ex_to_pseries(op).power_const(ex_to_numeric(it->coeff), order);
700 // Series multiplication
701 acc = ex_to_pseries(acc).mul_series(ex_to_pseries(op));
707 /** Compute the p-th power of a series.
709 * @param p power to compute
710 * @param deg truncation order of series calculation */
711 ex pseries::power_const(const numeric &p, int deg) const
714 const symbol *s = static_cast<symbol *>(var.bp);
715 int ldeg = ldegree(*s);
717 // Calculate coefficients of powered series
721 co.push_back(co0 = power(coeff(*s, ldeg), p));
722 bool all_sums_zero = true;
723 for (i=1; i<deg; i++) {
725 for (int j=1; j<=i; j++) {
726 ex c = coeff(*s, j + ldeg);
727 if (is_order_function(c)) {
728 co.push_back(Order(_ex1()));
731 sum += (p * j - (i - j)) * co[i - j] * c;
734 all_sums_zero = false;
735 co.push_back(co0 * sum / numeric(i));
738 // Construct new series (of non-zero coefficients)
740 bool higher_order = false;
741 for (i=0; i<deg; i++) {
742 if (!co[i].is_zero())
743 new_seq.push_back(expair(co[i], numeric(i) + p * ldeg));
744 if (is_order_function(co[i])) {
749 if (!higher_order && !all_sums_zero)
750 new_seq.push_back(expair(Order(_ex1()), numeric(deg) + p * ldeg));
751 return pseries(relational(var,point), new_seq);
755 /** Implementation of ex::series() for powers. This performs Laurent expansion
756 * of reciprocals of series at singularities.
758 ex power::series(const relational & r, int order) const
761 if (!is_ex_exactly_of_type(basis, pseries)) {
762 // Basis is not a series, may there be a singulary?
763 if (!exponent.info(info_flags::negint))
764 return basic::series(r, order);
766 // Expression is of type something^(-int), check for singularity
767 if (!basis.subs(r).is_zero())
768 return basic::series(r, order);
770 // Singularity encountered, expand basis into series
771 e = basis.series(r, order);
778 return ex_to_pseries(e).power_const(ex_to_numeric(exponent), order);
782 /** Re-expansion of a pseries object. */
783 ex pseries::series(const relational & r, int order) const
785 const ex p = r.rhs();
786 GINAC_ASSERT(is_ex_exactly_of_type(r.lhs(),symbol));
787 const symbol *s = static_cast<symbol *>(r.lhs().bp);
789 if (var.is_equal(*s) && point.is_equal(p)) {
790 if (order > degree(*s))
794 epvector::const_iterator it = seq.begin(), itend = seq.end();
795 while (it != itend) {
796 int o = ex_to_numeric(it->coeff).to_int();
798 new_seq.push_back(expair(Order(_ex1()), o));
801 new_seq.push_back(*it);
804 return pseries(r, new_seq);
807 return convert_to_poly().series(r, order);
811 /** Compute the truncated series expansion of an expression.
812 * This function returns an expression containing an object of class pseries
813 * to represent the series. If the series does not terminate within the given
814 * truncation order, the last term of the series will be an order term.
816 * @param r expansion relation, lhs holds variable and rhs holds point
817 * @param order truncation order of series calculations
818 * @return an expression holding a pseries object */
819 ex ex::series(const ex & r, int order) const
825 if (is_ex_exactly_of_type(r,relational))
826 rel_ = ex_to_relational(r);
827 else if (is_ex_exactly_of_type(r,symbol))
828 rel_ = relational(r,_ex0());
830 throw (std::logic_error("ex::series(): expansion point has unknown type"));
833 e = bp->series(rel_, order);
834 } catch (exception &x) {
835 throw (std::logic_error(string("unable to compute series (") + x.what() + ")"));
842 const pseries some_pseries;
843 const type_info & typeid_pseries = typeid(some_pseries);
845 #ifndef NO_NAMESPACE_GINAC
847 #endif // ndef NO_NAMESPACE_GINAC