coefficients of a polynomial in two or more variables
Subject: coefficients of a polynomial in two or more variables
From: reyssat
Date: Thu, 03 Dec 2009 10:47:04 +0100
Christian Stengg a ?crit :
> q:(a*x-b*y)*(4*x-y+1)+(c*x+d)*(y-2);
>
> But I would like to get the coefficients of the powers of x and y and of
> the mixed term x*y. I would like it best, if I could write a function
> that does this work automatically for any polynomial in two or more
> variables and returns a list of the coefficients. Can someone give me a
> hint how I could approach this problem?
>
Christian,
one way is to extract coefficients recursively. It may be a good idea to
keep only nonzero coefficients ; in this case you need of course to keep
track of which coefficient corresponds to which monomial.
So I suggest to construct a list of pairs, each formed by a coefficient
and a monomial. Or if the variables are given, replace each monomial by
the list of its exponents.
Here are two very similar functions, giving the coefficients and lists
of exponents (function f) or coefficients and monomials (function g) :
(%i2) f(p,L):=block([pp:expand(p),x:L[1],M,k,L2:[]],
if length(L)=1 then
(M:makelist([ratcoeff(pp,x,i),[i]],i,0,hipow(pp,x)),sublist(M,lambda([t],ev(t[1]#0,pred))))
else
(for k in f(pp,rest(L)) do
L2:append(L2,map(lambda([t],[t[1],append(k[2],t[2])]),f(k[1],[x]))),
L2))$
(%i3) g(p,L):=block([pp:expand(p),x:L[1],M,k,L2:[]],
if length(L)=1 then
(M:makelist([ratcoeff(pp,x,i),x^i],i,0,hipow(pp,x)),sublist(M,lambda([t],ev(t[1]#0,pred))))
else
(for k in g(pp,rest(L)) do
L2:append(L2,map(lambda([t],[t[1],k[2]*t[2]]),g(k[1],[x]))),
L2))$
And here is an example :
(%i4) q:(a*x-b*y)*(4*x-y+1)+(c*x+d)*(y-2);
(%o4) (-y+4*x+1)*(a*x-b*y)+(c*x+d)*(y-2)
(%i5) f(q,[x,y]);
(%o5)
[[-2*d,[0,0]],[a-2*c,[0,1]],[4*a,[0,2]],[d-b,[1,0]],[c-4*b-a,[1,1]],[b,[2,0]]]
(%i6) g(q,[x,y]);
(%o6) [[-2*d,1],[a-2*c,x],[4*a,x^2],[d-b,y],[c-4*b-a,x*y],[b,y^2]]
(%i7) g(q,[x,y,a]);
(%o7)
[[-2*d,1],[-2*c,x],[d-b,y],[c-4*b,x*y],[b,y^2],[1,a*x],[4,a*x^2],[-1,a*x*y]]
Eric