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++) {
169 if (i->rest.is_zero())
171 // print a sign, if needed
174 if (!is_order_function(i->rest)) {
175 // print 'rest', i.e. the expansion coefficient
176 if (i->rest.info(info_flags::numeric) &&
177 i->rest.info(info_flags::positive)) {
180 os << "(" << i->rest << ')';
181 // print 'coeff', something like (x-1)^42
182 if (!i->coeff.is_zero()) {
184 if (!point.is_zero())
185 os << '(' << var-point << ')';
188 if (i->coeff.compare(_ex1())) {
190 if (i->coeff.info(info_flags::negative))
191 os << '(' << i->coeff << ')';
197 os << Order(power(var-point,i->coeff));
202 void pseries::printraw(ostream &os) const
204 debugmsg("pseries printraw", LOGLEVEL_PRINT);
205 os << "pseries(" << var << ";" << point << ";";
206 for (epvector::const_iterator i=seq.begin(); i!=seq.end(); i++) {
207 os << "(" << (*i).rest << "," << (*i).coeff << "),";
212 void pseries::printtree(ostream & os, unsigned indent) const
214 debugmsg("pseries printtree",LOGLEVEL_PRINT);
215 os << string(indent,' ') << "pseries "
216 << ", hash=" << hashvalue << " (0x" << hex << hashvalue << dec << ")"
217 << ", flags=" << flags << endl;
218 for (unsigned i=0; i<seq.size(); ++i) {
219 seq[i].rest.printtree(os,indent+delta_indent);
220 seq[i].coeff.printtree(os,indent+delta_indent);
221 if (i!=seq.size()-1) {
222 os << string(indent+delta_indent,' ') << "-----" << endl;
225 var.printtree(os, indent+delta_indent);
226 point.printtree(os, indent+delta_indent);
229 unsigned pseries::nops(void) const
234 ex pseries::op(int i) const
236 if (i < 0 || unsigned(i) >= seq.size())
237 throw (std::out_of_range("op() out of range"));
238 return seq[i].rest * power(var - point, seq[i].coeff);
241 ex &pseries::let_op(int i)
243 throw (std::logic_error("let_op not defined for pseries"));
246 int pseries::degree(const symbol &s) const
248 if (var.is_equal(s)) {
249 // Return last exponent
251 return ex_to_numeric((*(seq.end() - 1)).coeff).to_int();
255 epvector::const_iterator it = seq.begin(), itend = seq.end();
258 int max_pow = INT_MIN;
259 while (it != itend) {
260 int pow = it->rest.degree(s);
269 int pseries::ldegree(const symbol &s) const
271 if (var.is_equal(s)) {
272 // Return first exponent
274 return ex_to_numeric((*(seq.begin())).coeff).to_int();
278 epvector::const_iterator it = seq.begin(), itend = seq.end();
281 int min_pow = INT_MAX;
282 while (it != itend) {
283 int pow = it->rest.ldegree(s);
292 ex pseries::coeff(const symbol &s, int n) const
294 if (var.is_equal(s)) {
298 // Binary search in sequence for given power
299 numeric looking_for = numeric(n);
300 int lo = 0, hi = seq.size() - 1;
302 int mid = (lo + hi) / 2;
303 GINAC_ASSERT(is_ex_exactly_of_type(seq[mid].coeff, numeric));
304 int cmp = ex_to_numeric(seq[mid].coeff).compare(looking_for);
310 return seq[mid].rest;
315 throw(std::logic_error("pseries::coeff: compare() didn't return -1, 0 or 1"));
320 return convert_to_poly().coeff(s, n);
323 ex pseries::collect(const symbol &s) const
328 /** Evaluate coefficients. */
329 ex pseries::eval(int level) const
334 if (level == -max_recursion_level)
335 throw (std::runtime_error("pseries::eval(): recursion limit exceeded"));
337 // Construct a new series with evaluated coefficients
339 new_seq.reserve(seq.size());
340 epvector::const_iterator it = seq.begin(), itend = seq.end();
341 while (it != itend) {
342 new_seq.push_back(expair(it->rest.eval(level-1), it->coeff));
345 return (new pseries(relational(var,point), new_seq))->setflag(status_flags::dynallocated | status_flags::evaluated);
348 /** Evaluate coefficients numerically. */
349 ex pseries::evalf(int level) const
354 if (level == -max_recursion_level)
355 throw (std::runtime_error("pseries::evalf(): recursion limit exceeded"));
357 // Construct a new series with evaluated coefficients
359 new_seq.reserve(seq.size());
360 epvector::const_iterator it = seq.begin(), itend = seq.end();
361 while (it != itend) {
362 new_seq.push_back(expair(it->rest.evalf(level-1), it->coeff));
365 return (new pseries(relational(var,point), new_seq))->setflag(status_flags::dynallocated | status_flags::evaluated);
368 ex pseries::subs(const lst & ls, const lst & lr) const
370 // If expansion variable is being substituted, convert the series to a
371 // polynomial and do the substitution there because the result might
372 // no longer be a power series
374 return convert_to_poly(true).subs(ls, lr);
376 // Otherwise construct a new series with substituted coefficients and
379 new_seq.reserve(seq.size());
380 epvector::const_iterator it = seq.begin(), itend = seq.end();
381 while (it != itend) {
382 new_seq.push_back(expair(it->rest.subs(ls, lr), it->coeff));
385 return (new pseries(relational(var,point.subs(ls, lr)), new_seq))->setflag(status_flags::dynallocated);
388 /** Implementation of ex::diff() for a power series. It treats the series as a
391 ex pseries::derivative(const symbol & s) const
395 epvector::const_iterator it = seq.begin(), itend = seq.end();
397 // FIXME: coeff might depend on var
398 while (it != itend) {
399 if (is_order_function(it->rest)) {
400 new_seq.push_back(expair(it->rest, it->coeff - 1));
402 ex c = it->rest * it->coeff;
404 new_seq.push_back(expair(c, it->coeff - 1));
408 return pseries(relational(var,point), new_seq);
416 * Construct ordinary polynomial out of series
419 /** Convert a pseries object to an ordinary polynomial.
421 * @param no_order flag: discard higher order terms */
422 ex pseries::convert_to_poly(bool no_order) const
425 epvector::const_iterator it = seq.begin(), itend = seq.end();
427 while (it != itend) {
428 if (is_order_function(it->rest)) {
430 e += Order(power(var - point, it->coeff));
432 e += it->rest * power(var - point, it->coeff);
440 * Implementation of series expansion
443 /** Default implementation of ex::series(). This performs Taylor expansion.
445 ex basic::series(const relational & r, int order) const
450 ex coeff = deriv.subs(r);
451 const symbol *s = static_cast<symbol *>(r.lhs().bp);
453 if (!coeff.is_zero())
454 seq.push_back(expair(coeff, numeric(0)));
457 for (n=1; n<order; n++) {
458 fac = fac.mul(numeric(n));
459 deriv = deriv.diff(*s).expand();
460 if (deriv.is_zero()) {
462 return pseries(r, seq);
464 coeff = fac.inverse() * deriv.subs(r);
465 if (!coeff.is_zero())
466 seq.push_back(expair(coeff, numeric(n)));
469 // Higher-order terms, if present
470 deriv = deriv.diff(*s);
471 if (!deriv.is_zero())
472 seq.push_back(expair(Order(_ex1()), numeric(n)));
473 return pseries(r, seq);
477 /** Implementation of ex::series() for symbols.
479 ex symbol::series(const relational & r, int order) const
482 const ex point = r.rhs();
483 GINAC_ASSERT(is_ex_exactly_of_type(r.lhs(),symbol));
484 const symbol *s = static_cast<symbol *>(r.lhs().bp);
486 if (this->is_equal(*s)) {
487 if (order > 0 && !point.is_zero())
488 seq.push_back(expair(point, _ex0()));
490 seq.push_back(expair(_ex1(), _ex1()));
492 seq.push_back(expair(Order(_ex1()), numeric(order)));
494 seq.push_back(expair(*this, _ex0()));
495 return pseries(r, seq);
499 /** Add one series object to another, producing a pseries object that
500 * represents the sum.
502 * @param other pseries object to add with
503 * @return the sum as a pseries */
504 ex pseries::add_series(const pseries &other) const
506 // Adding two series with different variables or expansion points
507 // results in an empty (constant) series
508 if (!is_compatible_to(other)) {
510 nul.push_back(expair(Order(_ex1()), _ex0()));
511 return pseries(relational(var,point), nul);
516 epvector::const_iterator a = seq.begin();
517 epvector::const_iterator b = other.seq.begin();
518 epvector::const_iterator a_end = seq.end();
519 epvector::const_iterator b_end = other.seq.end();
520 int pow_a = INT_MAX, pow_b = INT_MAX;
522 // If a is empty, fill up with elements from b and stop
525 new_seq.push_back(*b);
530 pow_a = ex_to_numeric((*a).coeff).to_int();
532 // If b is empty, fill up with elements from a and stop
535 new_seq.push_back(*a);
540 pow_b = ex_to_numeric((*b).coeff).to_int();
542 // a and b are non-empty, compare powers
544 // a has lesser power, get coefficient from a
545 new_seq.push_back(*a);
546 if (is_order_function((*a).rest))
549 } else if (pow_b < pow_a) {
550 // b has lesser power, get coefficient from b
551 new_seq.push_back(*b);
552 if (is_order_function((*b).rest))
556 // Add coefficient of a and b
557 if (is_order_function((*a).rest) || is_order_function((*b).rest)) {
558 new_seq.push_back(expair(Order(_ex1()), (*a).coeff));
559 break; // Order term ends the sequence
561 ex sum = (*a).rest + (*b).rest;
562 if (!(sum.is_zero()))
563 new_seq.push_back(expair(sum, numeric(pow_a)));
569 return pseries(relational(var,point), new_seq);
573 /** Implementation of ex::series() for sums. This performs series addition when
574 * adding pseries objects.
576 ex add::series(const relational & r, int order) const
578 ex acc; // Series accumulator
580 // Get first term from overall_coeff
581 acc = overall_coeff.series(r, order);
583 // Add remaining terms
584 epvector::const_iterator it = seq.begin();
585 epvector::const_iterator itend = seq.end();
586 for (; it!=itend; it++) {
588 if (is_ex_exactly_of_type(it->rest, pseries))
591 op = it->rest.series(r, order);
592 if (!it->coeff.is_equal(_ex1()))
593 op = ex_to_pseries(op).mul_const(ex_to_numeric(it->coeff));
596 acc = ex_to_pseries(acc).add_series(ex_to_pseries(op));
602 /** Multiply a pseries object with a numeric constant, producing a pseries
603 * object that represents the product.
605 * @param other constant to multiply with
606 * @return the product as a pseries */
607 ex pseries::mul_const(const numeric &other) const
610 new_seq.reserve(seq.size());
612 epvector::const_iterator it = seq.begin(), itend = seq.end();
613 while (it != itend) {
614 if (!is_order_function(it->rest))
615 new_seq.push_back(expair(it->rest * other, it->coeff));
617 new_seq.push_back(*it);
620 return pseries(relational(var,point), new_seq);
624 /** Multiply one pseries object to another, producing a pseries object that
625 * represents the product.
627 * @param other pseries object to multiply with
628 * @return the product as a pseries */
629 ex pseries::mul_series(const pseries &other) const
631 // Multiplying two series with different variables or expansion points
632 // results in an empty (constant) series
633 if (!is_compatible_to(other)) {
635 nul.push_back(expair(Order(_ex1()), _ex0()));
636 return pseries(relational(var,point), nul);
639 // Series multiplication
642 const symbol *s = static_cast<symbol *>(var.bp);
643 int a_max = degree(*s);
644 int b_max = other.degree(*s);
645 int a_min = ldegree(*s);
646 int b_min = other.ldegree(*s);
647 int cdeg_min = a_min + b_min;
648 int cdeg_max = a_max + b_max;
650 int higher_order_a = INT_MAX;
651 int higher_order_b = INT_MAX;
652 if (is_order_function(coeff(*s, a_max)))
653 higher_order_a = a_max + b_min;
654 if (is_order_function(other.coeff(*s, b_max)))
655 higher_order_b = b_max + a_min;
656 int higher_order_c = min(higher_order_a, higher_order_b);
657 if (cdeg_max >= higher_order_c)
658 cdeg_max = higher_order_c - 1;
660 for (int cdeg=cdeg_min; cdeg<=cdeg_max; cdeg++) {
662 // c(i)=a(0)b(i)+...+a(i)b(0)
663 for (int i=a_min; cdeg-i>=b_min; i++) {
664 ex a_coeff = coeff(*s, i);
665 ex b_coeff = other.coeff(*s, cdeg-i);
666 if (!is_order_function(a_coeff) && !is_order_function(b_coeff))
667 co += a_coeff * b_coeff;
670 new_seq.push_back(expair(co, numeric(cdeg)));
672 if (higher_order_c < INT_MAX)
673 new_seq.push_back(expair(Order(_ex1()), numeric(higher_order_c)));
674 return pseries(relational(var,point), new_seq);
678 /** Implementation of ex::series() for product. This performs series
679 * multiplication when multiplying series.
681 ex mul::series(const relational & r, int order) const
683 ex acc; // Series accumulator
685 // Get first term from overall_coeff
686 acc = overall_coeff.series(r, order);
688 // Multiply with remaining terms
689 epvector::const_iterator it = seq.begin();
690 epvector::const_iterator itend = seq.end();
691 for (; it!=itend; it++) {
693 if (op.info(info_flags::numeric)) {
694 // series * const (special case, faster)
695 ex f = power(op, it->coeff);
696 acc = ex_to_pseries(acc).mul_const(ex_to_numeric(f));
698 } else if (!is_ex_exactly_of_type(op, pseries))
699 op = op.series(r, order);
700 if (!it->coeff.is_equal(_ex1()))
701 op = ex_to_pseries(op).power_const(ex_to_numeric(it->coeff), order);
703 // Series multiplication
704 acc = ex_to_pseries(acc).mul_series(ex_to_pseries(op));
710 /** Compute the p-th power of a series.
712 * @param p power to compute
713 * @param deg truncation order of series calculation */
714 ex pseries::power_const(const numeric &p, int deg) const
717 const symbol *s = static_cast<symbol *>(var.bp);
718 int ldeg = ldegree(*s);
720 // Calculate coefficients of powered series
724 co.push_back(co0 = power(coeff(*s, ldeg), p));
725 bool all_sums_zero = true;
726 for (i=1; i<deg; i++) {
728 for (int j=1; j<=i; j++) {
729 ex c = coeff(*s, j + ldeg);
730 if (is_order_function(c)) {
731 co.push_back(Order(_ex1()));
734 sum += (p * j - (i - j)) * co[i - j] * c;
737 all_sums_zero = false;
738 co.push_back(co0 * sum / numeric(i));
741 // Construct new series (of non-zero coefficients)
743 bool higher_order = false;
744 for (i=0; i<deg; i++) {
745 if (!co[i].is_zero())
746 new_seq.push_back(expair(co[i], numeric(i) + p * ldeg));
747 if (is_order_function(co[i])) {
752 if (!higher_order && !all_sums_zero)
753 new_seq.push_back(expair(Order(_ex1()), numeric(deg) + p * ldeg));
754 return pseries(relational(var,point), new_seq);
758 /** Implementation of ex::series() for powers. This performs Laurent expansion
759 * of reciprocals of series at singularities.
761 ex power::series(const relational & r, int order) const
764 if (!is_ex_exactly_of_type(basis, pseries)) {
765 // Basis is not a series, may there be a singulary?
766 if (!exponent.info(info_flags::negint))
767 return basic::series(r, order);
769 // Expression is of type something^(-int), check for singularity
770 if (!basis.subs(r).is_zero())
771 return basic::series(r, order);
773 // Singularity encountered, expand basis into series
774 e = basis.series(r, order);
781 return ex_to_pseries(e).power_const(ex_to_numeric(exponent), order);
785 /** Re-expansion of a pseries object. */
786 ex pseries::series(const relational & r, int order) const
788 const ex p = r.rhs();
789 GINAC_ASSERT(is_ex_exactly_of_type(r.lhs(),symbol));
790 const symbol *s = static_cast<symbol *>(r.lhs().bp);
792 if (var.is_equal(*s) && point.is_equal(p)) {
793 if (order > degree(*s))
797 epvector::const_iterator it = seq.begin(), itend = seq.end();
798 while (it != itend) {
799 int o = ex_to_numeric(it->coeff).to_int();
801 new_seq.push_back(expair(Order(_ex1()), o));
804 new_seq.push_back(*it);
807 return pseries(r, new_seq);
810 return convert_to_poly().series(r, order);
814 /** Compute the truncated series expansion of an expression.
815 * This function returns an expression containing an object of class pseries
816 * to represent the series. If the series does not terminate within the given
817 * truncation order, the last term of the series will be an order term.
819 * @param r expansion relation, lhs holds variable and rhs holds point
820 * @param order truncation order of series calculations
821 * @return an expression holding a pseries object */
822 ex ex::series(const ex & r, int order) const
828 if (is_ex_exactly_of_type(r,relational))
829 rel_ = ex_to_relational(r);
830 else if (is_ex_exactly_of_type(r,symbol))
831 rel_ = relational(r,_ex0());
833 throw (std::logic_error("ex::series(): expansion point has unknown type"));
836 e = bp->series(rel_, order);
837 } catch (exception &x) {
838 throw (std::logic_error(string("unable to compute series (") + x.what() + ")"));
845 const pseries some_pseries;
846 const type_info & typeid_pseries = typeid(some_pseries);
848 #ifndef NO_NAMESPACE_GINAC
850 #endif // ndef NO_NAMESPACE_GINAC