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);
156 * Functions overriding virtual functions from base classes
159 basic *pseries::duplicate() const
161 debugmsg("pseries duplicate", LOGLEVEL_DUPLICATE);
162 return new pseries(*this);
165 void pseries::print(ostream &os, unsigned upper_precedence) const
167 debugmsg("pseries print", LOGLEVEL_PRINT);
168 // This could be made better, since series expansion at x==1 might print
169 // -1+2*x+Order((-1+x)^2) instead of 1+2*(-1+x)+Order((-1+x)^2), which is
170 // correct but can be rather confusing.
171 convert_to_poly().print(os, upper_precedence);
174 void pseries::printraw(ostream &os) const
176 debugmsg("pseries printraw", LOGLEVEL_PRINT);
177 os << "pseries(" << var << ";" << point << ";";
178 for (epvector::const_iterator i=seq.begin(); i!=seq.end(); i++) {
179 os << "(" << (*i).rest << "," << (*i).coeff << "),";
184 void pseries::printtree(ostream & os, unsigned indent) const
186 debugmsg("pseries printtree",LOGLEVEL_PRINT);
187 os << string(indent,' ') << "pseries "
188 << ", hash=" << hashvalue << " (0x" << hex << hashvalue << dec << ")"
189 << ", flags=" << flags << endl;
190 for (unsigned i=0; i<seq.size(); ++i) {
191 seq[i].rest.printtree(os,indent+delta_indent);
192 seq[i].coeff.printtree(os,indent+delta_indent);
193 if (i!=seq.size()-1) {
194 os << string(indent+delta_indent,' ') << "-----" << endl;
197 var.printtree(os, indent+delta_indent);
198 point.printtree(os, indent+delta_indent);
201 unsigned pseries::nops(void) const
206 ex pseries::op(int i) const
208 if (i < 0 || unsigned(i) >= seq.size())
209 throw (std::out_of_range("op() out of range"));
210 return seq[i].rest * power(var - point, seq[i].coeff);
213 ex &pseries::let_op(int i)
215 throw (std::logic_error("let_op not defined for pseries"));
218 int pseries::degree(const symbol &s) const
220 if (var.is_equal(s)) {
221 // Return last exponent
223 return ex_to_numeric((*(seq.end() - 1)).coeff).to_int();
227 epvector::const_iterator it = seq.begin(), itend = seq.end();
230 int max_pow = INT_MIN;
231 while (it != itend) {
232 int pow = it->rest.degree(s);
241 int pseries::ldegree(const symbol &s) const
243 if (var.is_equal(s)) {
244 // Return first exponent
246 return ex_to_numeric((*(seq.begin())).coeff).to_int();
250 epvector::const_iterator it = seq.begin(), itend = seq.end();
253 int min_pow = INT_MAX;
254 while (it != itend) {
255 int pow = it->rest.ldegree(s);
264 ex pseries::coeff(const symbol &s, int n) const
266 if (var.is_equal(s)) {
270 // Binary search in sequence for given power
271 numeric looking_for = numeric(n);
272 int lo = 0, hi = seq.size() - 1;
274 int mid = (lo + hi) / 2;
275 GINAC_ASSERT(is_ex_exactly_of_type(seq[mid].coeff, numeric));
276 int cmp = ex_to_numeric(seq[mid].coeff).compare(looking_for);
282 return seq[mid].rest;
287 throw(std::logic_error("pseries::coeff: compare() didn't return -1, 0 or 1"));
292 return convert_to_poly().coeff(s, n);
295 ex pseries::collect(const symbol &s) const
300 /** Evaluate coefficients. */
301 ex pseries::eval(int level) const
306 if (level == -max_recursion_level)
307 throw (std::runtime_error("pseries::eval(): recursion limit exceeded"));
309 // Construct a new series with evaluated coefficients
311 new_seq.reserve(seq.size());
312 epvector::const_iterator it = seq.begin(), itend = seq.end();
313 while (it != itend) {
314 new_seq.push_back(expair(it->rest.eval(level-1), it->coeff));
317 return (new pseries(relational(var,point), new_seq))->setflag(status_flags::dynallocated | status_flags::evaluated);
320 /** Evaluate coefficients numerically. */
321 ex pseries::evalf(int level) const
326 if (level == -max_recursion_level)
327 throw (std::runtime_error("pseries::evalf(): recursion limit exceeded"));
329 // Construct a new series with evaluated coefficients
331 new_seq.reserve(seq.size());
332 epvector::const_iterator it = seq.begin(), itend = seq.end();
333 while (it != itend) {
334 new_seq.push_back(expair(it->rest.evalf(level-1), it->coeff));
337 return (new pseries(relational(var,point), new_seq))->setflag(status_flags::dynallocated | status_flags::evaluated);
340 ex pseries::subs(const lst & ls, const lst & lr) const
342 // If expansion variable is being substituted, convert the series to a
343 // polynomial and do the substitution there because the result might
344 // no longer be a power series
346 return convert_to_poly(true).subs(ls, lr);
348 // Otherwise construct a new series with substituted coefficients and
351 new_seq.reserve(seq.size());
352 epvector::const_iterator it = seq.begin(), itend = seq.end();
353 while (it != itend) {
354 new_seq.push_back(expair(it->rest.subs(ls, lr), it->coeff));
357 return (new pseries(relational(var,point.subs(ls, lr)), new_seq))->setflag(status_flags::dynallocated);
360 /** Implementation of ex::diff() for a power series. It treats the series as a
363 ex pseries::derivative(const symbol & s) const
367 epvector::const_iterator it = seq.begin(), itend = seq.end();
369 // FIXME: coeff might depend on var
370 while (it != itend) {
371 if (is_order_function(it->rest)) {
372 new_seq.push_back(expair(it->rest, it->coeff - 1));
374 ex c = it->rest * it->coeff;
376 new_seq.push_back(expair(c, it->coeff - 1));
380 return pseries(relational(var,point), new_seq);
388 * Construct ordinary polynomial out of series
391 /** Convert a pseries object to an ordinary polynomial.
393 * @param no_order flag: discard higher order terms */
394 ex pseries::convert_to_poly(bool no_order) const
397 epvector::const_iterator it = seq.begin(), itend = seq.end();
399 while (it != itend) {
400 if (is_order_function(it->rest)) {
402 e += Order(power(var - point, it->coeff));
404 e += it->rest * power(var - point, it->coeff);
412 * Implementation of series expansion
415 /** Default implementation of ex::series(). This performs Taylor expansion.
417 ex basic::series(const relational & r, int order) const
422 ex coeff = deriv.subs(r);
423 const symbol *s = static_cast<symbol *>(r.lhs().bp);
425 if (!coeff.is_zero())
426 seq.push_back(expair(coeff, numeric(0)));
429 for (n=1; n<order; n++) {
430 fac = fac.mul(numeric(n));
431 deriv = deriv.diff(*s).expand();
432 if (deriv.is_zero()) {
434 return pseries(r, seq);
436 coeff = fac.inverse() * deriv.subs(r);
437 if (!coeff.is_zero())
438 seq.push_back(expair(coeff, numeric(n)));
441 // Higher-order terms, if present
442 deriv = deriv.diff(*s);
443 if (!deriv.is_zero())
444 seq.push_back(expair(Order(_ex1()), numeric(n)));
445 return pseries(r, seq);
449 /** Implementation of ex::series() for symbols.
451 ex symbol::series(const relational & r, int order) const
454 const ex point = r.rhs();
455 GINAC_ASSERT(is_ex_exactly_of_type(r.lhs(),symbol));
456 const symbol *s = static_cast<symbol *>(r.lhs().bp);
458 if (this->is_equal(*s)) {
459 if (order > 0 && !point.is_zero())
460 seq.push_back(expair(point, _ex0()));
462 seq.push_back(expair(_ex1(), _ex1()));
464 seq.push_back(expair(Order(_ex1()), numeric(order)));
466 seq.push_back(expair(*this, _ex0()));
467 return pseries(r, seq);
471 /** Add one series object to another, producing a pseries object that
472 * represents the sum.
474 * @param other pseries object to add with
475 * @return the sum as a pseries */
476 ex pseries::add_series(const pseries &other) const
478 // Adding two series with different variables or expansion points
479 // results in an empty (constant) series
480 if (!is_compatible_to(other)) {
482 nul.push_back(expair(Order(_ex1()), _ex0()));
483 return pseries(relational(var,point), nul);
488 epvector::const_iterator a = seq.begin();
489 epvector::const_iterator b = other.seq.begin();
490 epvector::const_iterator a_end = seq.end();
491 epvector::const_iterator b_end = other.seq.end();
492 int pow_a = INT_MAX, pow_b = INT_MAX;
494 // If a is empty, fill up with elements from b and stop
497 new_seq.push_back(*b);
502 pow_a = ex_to_numeric((*a).coeff).to_int();
504 // If b is empty, fill up with elements from a and stop
507 new_seq.push_back(*a);
512 pow_b = ex_to_numeric((*b).coeff).to_int();
514 // a and b are non-empty, compare powers
516 // a has lesser power, get coefficient from a
517 new_seq.push_back(*a);
518 if (is_order_function((*a).rest))
521 } else if (pow_b < pow_a) {
522 // b has lesser power, get coefficient from b
523 new_seq.push_back(*b);
524 if (is_order_function((*b).rest))
528 // Add coefficient of a and b
529 if (is_order_function((*a).rest) || is_order_function((*b).rest)) {
530 new_seq.push_back(expair(Order(_ex1()), (*a).coeff));
531 break; // Order term ends the sequence
533 ex sum = (*a).rest + (*b).rest;
534 if (!(sum.is_zero()))
535 new_seq.push_back(expair(sum, numeric(pow_a)));
541 return pseries(relational(var,point), new_seq);
545 /** Implementation of ex::series() for sums. This performs series addition when
546 * adding pseries objects.
548 ex add::series(const relational & r, int order) const
550 ex acc; // Series accumulator
552 // Get first term from overall_coeff
553 acc = overall_coeff.series(r, order);
555 // Add remaining terms
556 epvector::const_iterator it = seq.begin();
557 epvector::const_iterator itend = seq.end();
558 for (; it!=itend; it++) {
560 if (is_ex_exactly_of_type(it->rest, pseries))
563 op = it->rest.series(r, order);
564 if (!it->coeff.is_equal(_ex1()))
565 op = ex_to_pseries(op).mul_const(ex_to_numeric(it->coeff));
568 acc = ex_to_pseries(acc).add_series(ex_to_pseries(op));
574 /** Multiply a pseries object with a numeric constant, producing a pseries
575 * object that represents the product.
577 * @param other constant to multiply with
578 * @return the product as a pseries */
579 ex pseries::mul_const(const numeric &other) const
582 new_seq.reserve(seq.size());
584 epvector::const_iterator it = seq.begin(), itend = seq.end();
585 while (it != itend) {
586 if (!is_order_function(it->rest))
587 new_seq.push_back(expair(it->rest * other, it->coeff));
589 new_seq.push_back(*it);
592 return pseries(relational(var,point), new_seq);
596 /** Multiply one pseries object to another, producing a pseries object that
597 * represents the product.
599 * @param other pseries object to multiply with
600 * @return the product as a pseries */
601 ex pseries::mul_series(const pseries &other) const
603 // Multiplying two series with different variables or expansion points
604 // results in an empty (constant) series
605 if (!is_compatible_to(other)) {
607 nul.push_back(expair(Order(_ex1()), _ex0()));
608 return pseries(relational(var,point), nul);
611 // Series multiplication
614 const symbol *s = static_cast<symbol *>(var.bp);
615 int a_max = degree(*s);
616 int b_max = other.degree(*s);
617 int a_min = ldegree(*s);
618 int b_min = other.ldegree(*s);
619 int cdeg_min = a_min + b_min;
620 int cdeg_max = a_max + b_max;
622 int higher_order_a = INT_MAX;
623 int higher_order_b = INT_MAX;
624 if (is_order_function(coeff(*s, a_max)))
625 higher_order_a = a_max + b_min;
626 if (is_order_function(other.coeff(*s, b_max)))
627 higher_order_b = b_max + a_min;
628 int higher_order_c = min(higher_order_a, higher_order_b);
629 if (cdeg_max >= higher_order_c)
630 cdeg_max = higher_order_c - 1;
632 for (int cdeg=cdeg_min; cdeg<=cdeg_max; cdeg++) {
634 // c(i)=a(0)b(i)+...+a(i)b(0)
635 for (int i=a_min; cdeg-i>=b_min; i++) {
636 ex a_coeff = coeff(*s, i);
637 ex b_coeff = other.coeff(*s, cdeg-i);
638 if (!is_order_function(a_coeff) && !is_order_function(b_coeff))
639 co += coeff(*s, i) * other.coeff(*s, cdeg-i);
642 new_seq.push_back(expair(co, numeric(cdeg)));
644 if (higher_order_c < INT_MAX)
645 new_seq.push_back(expair(Order(_ex1()), numeric(higher_order_c)));
646 return pseries(relational(var,point), new_seq);
650 /** Implementation of ex::series() for product. This performs series
651 * multiplication when multiplying series.
653 ex mul::series(const relational & r, int order) const
655 ex acc; // Series accumulator
657 // Get first term from overall_coeff
658 acc = overall_coeff.series(r, order);
660 // Multiply with remaining terms
661 epvector::const_iterator it = seq.begin();
662 epvector::const_iterator itend = seq.end();
663 for (; it!=itend; it++) {
665 if (op.info(info_flags::numeric)) {
666 // series * const (special case, faster)
667 ex f = power(op, it->coeff);
668 acc = ex_to_pseries(acc).mul_const(ex_to_numeric(f));
670 } else if (!is_ex_exactly_of_type(op, pseries))
671 op = op.series(r, order);
672 if (!it->coeff.is_equal(_ex1()))
673 op = ex_to_pseries(op).power_const(ex_to_numeric(it->coeff), order);
675 // Series multiplication
676 acc = ex_to_pseries(acc).mul_series(ex_to_pseries(op));
682 /** Compute the p-th power of a series.
684 * @param p power to compute
685 * @param deg truncation order of series calculation */
686 ex pseries::power_const(const numeric &p, int deg) const
689 const symbol *s = static_cast<symbol *>(var.bp);
690 int ldeg = ldegree(*s);
692 // Calculate coefficients of powered series
696 co.push_back(co0 = power(coeff(*s, ldeg), p));
697 bool all_sums_zero = true;
698 for (i=1; i<deg; i++) {
700 for (int j=1; j<=i; j++) {
701 ex c = coeff(*s, j + ldeg);
702 if (is_order_function(c)) {
703 co.push_back(Order(_ex1()));
706 sum += (p * j - (i - j)) * co[i - j] * c;
709 all_sums_zero = false;
710 co.push_back(co0 * sum / numeric(i));
713 // Construct new series (of non-zero coefficients)
715 bool higher_order = false;
716 for (i=0; i<deg; i++) {
717 if (!co[i].is_zero())
718 new_seq.push_back(expair(co[i], numeric(i) + p * ldeg));
719 if (is_order_function(co[i])) {
724 if (!higher_order && !all_sums_zero)
725 new_seq.push_back(expair(Order(_ex1()), numeric(deg) + p * ldeg));
726 return pseries(relational(var,point), new_seq);
730 /** Implementation of ex::series() for powers. This performs Laurent expansion
731 * of reciprocals of series at singularities.
733 ex power::series(const relational & r, int order) const
736 if (!is_ex_exactly_of_type(basis, pseries)) {
737 // Basis is not a series, may there be a singulary?
738 if (!exponent.info(info_flags::negint))
739 return basic::series(r, order);
741 // Expression is of type something^(-int), check for singularity
742 if (!basis.subs(r).is_zero())
743 return basic::series(r, order);
745 // Singularity encountered, expand basis into series
746 e = basis.series(r, order);
753 return ex_to_pseries(e).power_const(ex_to_numeric(exponent), order);
757 /** Re-expansion of a pseries object. */
758 ex pseries::series(const relational & r, int order) const
760 const ex p = r.rhs();
761 GINAC_ASSERT(is_ex_exactly_of_type(r.lhs(),symbol));
762 const symbol *s = static_cast<symbol *>(r.lhs().bp);
764 if (var.is_equal(*s) && point.is_equal(p)) {
765 if (order > degree(*s))
769 epvector::const_iterator it = seq.begin(), itend = seq.end();
770 while (it != itend) {
771 int o = ex_to_numeric(it->coeff).to_int();
773 new_seq.push_back(expair(Order(_ex1()), o));
776 new_seq.push_back(*it);
779 return pseries(r, new_seq);
782 return convert_to_poly().series(r, order);
786 /** Compute the truncated series expansion of an expression.
787 * This function returns an expression containing an object of class pseries
788 * to represent the series. If the series does not terminate within the given
789 * truncation order, the last term of the series will be an order term.
791 * @param r expansion relation, lhs holds variable and rhs holds point
792 * @param order truncation order of series calculations
793 * @return an expression holding a pseries object */
794 ex ex::series(const ex & r, int order) const
800 if (is_ex_exactly_of_type(r,relational))
801 rel_ = ex_to_relational(r);
802 else if (is_ex_exactly_of_type(r,symbol))
803 rel_ = relational(r,_ex0());
805 throw (std::logic_error("ex::series(): expansion point has unknown type"));
808 e = bp->series(rel_, order);
809 } catch (exception &x) {
810 throw (std::logic_error(string("unable to compute series (") + x.what() + ")"));
817 const pseries some_pseries;
818 const type_info & typeid_pseries = typeid(some_pseries);
820 #ifndef NO_NAMESPACE_GINAC
822 #endif // ndef NO_NAMESPACE_GINAC