Natavi
Natavi

Reputation: 25

How to check if a sympy function is odd?

I'm a bit of a beginner to sympy, so please don't assume too much library-specific knowledge on my end.

I'm integrating over an even domain the sum of many exponential expressions, and to speed up that process I'd like to ignore any term that's odd. For instance, the expression

        #   / pi  / pi  / pi
        #  |     |     |
        #  |     |     |   exp(-I*x1)exp(I*2*y)exp(I*5*z)  
        #  |     |     |   _____________________________ dx1 dy dz
        #  |     |     |              101
        #  |     |     |  
        # / -pi / -pi / -pi

is 0 because of the integral of e^{i2y} over the even domain (this works for e^{inx} for any even n > 0).

I've created a few thousand such terms and separated them into a list using Add.make_args(); a portion of that list is

[exp(I*x1)/4 - 1/2 + exp(-I*x1)/4, 
exp(I*x1/2)*exp(-I*y1/2)*exp(-I*z1/2)/2 + exp(-I*x1/2)*exp(I*y1/2)*exp(I*z1/2)/2]

For an individual exp() function, I know how to extract the argument using

f = exp(I*x1)/4
print(log(numer(f)).subs(x1,1)/I)

which prints

1

which I can then test using %2==0. However, I'm not sure how to scan across multiple consecutive exp() functions each of which may have one of 6 different integration variables, or if there's an easier way to do this.

How do I check if a multivariate sympy function is odd, or extract each of its exp() arguments to examine?

(edit: changed my method of testing if integer is even; added python tag)

Upvotes: 0

Views: 492

Answers (1)

smichr
smichr

Reputation: 19077

So you are trying to find exponents that are imaginary that have an even coefficient?

Let v be a list of your variables of integration and eq your integrand (or numerator of the same), then

from sympy import exp, I, Symbol
v = x, y = symbols('x y')
eq = exp(2*x)*exp(2*I*x)*exp(3*I*y)
print(eq.replace(lambda e:
    e.func==exp and
    e.exp.is_Mul and I in e.exp.args and
    e.exp.coeff(I).as_independent(*v)[0].is_even,
lambda x: Symbol('o')))

prints

o*exp(2*x)*exp(3*I*y)

If you replace Symbol('o') with 0 the expression will collapse to 0.

Upvotes: 0

Related Questions