[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
5.7.3 Degree and coefficients
The degree and low degree of a polynomial can be obtained using the two methods
int ex::degree(const ex & s); int ex::ldegree(const ex & s); |
which also work reliably on non-expanded input polynomials (they even work on rational functions, returning the asymptotic degree). By definition, the degree of zero is zero. To extract a coefficient with a certain power from an expanded polynomial you use
ex ex::coeff(const ex & s, int n); |
You can also obtain the leading and trailing coefficients with the methods
ex ex::lcoeff(const ex & s); ex ex::tcoeff(const ex & s); |
which are equivalent to coeff(s, degree(s))
and coeff(s, ldegree(s))
,
respectively.
An application is illustrated in the next example, where a multivariate polynomial is analyzed:
{ symbol x("x"), y("y"); ex PolyInp = 4*pow(x,3)*y + 5*x*pow(y,2) + 3*y - pow(x+y,2) + 2*pow(y+2,2) - 8; ex Poly = PolyInp.expand(); for (int i=Poly.ldegree(x); i<=Poly.degree(x); ++i) { cout << "The x^" << i << "-coefficient is " << Poly.coeff(x,i) << endl; } cout << "As polynomial in y: " << Poly.collect(y) << endl; } |
When run, it returns an output in the following fashion:
The x^0-coefficient is y^2+11*y The x^1-coefficient is 5*y^2-2*y The x^2-coefficient is -1 The x^3-coefficient is 4*y As polynomial in y: -x^2+(5*x+1)*y^2+(-2*x+4*x^3+11)*y |
As always, the exact output may vary between different versions of GiNaC or even from run to run since the internal canonical ordering is not within the user's sphere of influence.
degree()
, ldegree()
, coeff()
, lcoeff()
,
tcoeff()
and collect()
can also be used to a certain degree
with non-polynomial expressions as they not only work with symbols but with
constants, functions and indexed objects as well:
{ symbol a("a"), b("b"), c("c"), x("x"); idx i(symbol("i"), 3); ex e = pow(sin(x) - cos(x), 4); cout << e.degree(cos(x)) << endl; // -> 4 cout << e.expand().coeff(sin(x), 3) << endl; // -> -4*cos(x) e = indexed(a+b, i) * indexed(b+c, i); e = e.expand(expand_options::expand_indexed); cout << e.collect(indexed(b, i)) << endl; // -> a.i*c.i+(a.i+c.i)*b.i+b.i^2 } |
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |