If I have a polynomial in terms of x, is it possible to extract the coefficient of x^2 easily (without copying and pasting)?
The coefficients of the polynomial are large and ugly and not worth typing out.
If there's no command for getting the coefficient, perhaps I could map my polynomial (which is, say, P=ax^3 + bx^2 + cx+d) to a vector space where x^3 = (1, 0, 0) = v1, x^2 = (0, 1, 0 ) = v2, x = (0,0,1) = v3 and P = av1 + bv2 + cv3 + d. And then the coefficient of b would be the dot product of P with v2. But I don't know how to do this either!
use coeff
Eg:
p := 2*x^2 + 3*x - 5: coeff(p,x,2); 2
Thanks!
Thanks!
collect
There is also collect to do all powers at once
f := (a*x+b)*(c*x+d)^2;
f := (a*x+b)*(c*x+d)^2
coeff(f,x,2);
b*c^2+2*a*d*c
collect(f,x);
a*c^2*x^3+(b*c^2+2*a*d*c)*x^2+(2*b*d*c+a*d^2)*x+b*d^2
---
G A Edgar
PolynomialTools[CoefficientList]
If you do want to get the polynomial as a vector or list of its coefficients, there is command to do that as well:
?PolynomialTools,CoefficientList
John
And that is the fastest way to do it
at least for large polynomials. PolynomialTools[CoefficientVector] is "better" in that it can handle sparse polynomials, which CoefficientList will necessarily make sense. PolynomialTools[CoefficientVector] is O(#terms), with subsequent extraction O(1), while coeff is O(#terms) [so that extracting all coefficients is O(#terms^2) ].
I am rather happy with that code -- that was one of the last routines which I added to Maple. Although some of the credit should go to Bruno Salvy, who first pointed out the frequent Maple anti-pattern of using coeff in a loop, and a better solution, which became the heart of PolynomialTools[CoefficientVector].