# Filtering an expression: keeping only term with even power

In the expression $$x^2 y^2+x y^2+x^3y + 5 x^4 y^4$$ I would like to keep only the term where the variables have even power $$x^2y^2+5 x^4 y^4$$

Is there a way to do it?

I look into this post.
But once I get the operands, I don't see how to analyze the variable exponent.

edit retag close merge delete

Sort by ยป oldest newest most voted

Is that what you need?

var('x y');
p=(5*x^2*y^2+x*y^2+x^3*y+x^4*y^4).polynomial(QQ)
sum([v[0]*v[1] for v in p if forall(v[1].exponents()[0],lambda x:is_even(x))[0]])
#x^4*y^4 + 5*x^2*y^2

more

@archrzesz Exactly what I want, thank you. Is there a way to keep the coefficient of each monomial? For example, return $5 x^4 y^4$.

( 2012-10-22 20:42:54 +0100 )edit

I've edited my answer according to the Nicolas request. Notice that my answer works for many variables. Just change var and p.

( 2012-10-23 03:14:50 +0100 )edit

@achrzesz Very flexible approach. Thank you.

( 2012-10-23 07:35:57 +0100 )edit

The following also works, although it might not be as flexible as the answer by @achrzesz, which handles things nicely.

x, y = var('x, y')
f(x,y)=x^2*y^2-4*x^2*y+2*y^2+4*x*y^4-3*x^4*y^6
g(x,y)=(f(x,y)+f(-x,y))/2
h(x,y)=(g(x,y)+g(x,-y))/2
h

more

Here is an answer using the list command and some list comprehensions.

var('x y')
R.<x,y>=PolynomialRing(RR)
q=x^2*y^2+x+x^2*y+y^2
terms=list(q)
ans=[t[0]*t[1] for t in terms if (t[1].degree(x) % 2)==0 and (t[1].degree(y) % 2==0)]
sum(ans)


This will also keep the coefficients.

more