Ask Your Question

Revision history [back]

How to define a function that is piecewise for specific independent variable values

I'm solving for the coefficients of a fourier series, where the function to be approximated is

f(x) is 0 from -pi to +pi/2, and +1 from pi/2 to pi. It then repeats over all periods. The equation for the coefficients, c_n is (1/2pi)*int_-pi^pi f(x)e^{-inx}dx.

I've solved these to be c_0 = 1/4, c_n=1,5,...=-(1+i)/n, c_n=2,6,...=2i/n, c_n=3,7,...=(1-i)/n and c_n=4,8,...=0.

Now I'd like to check my work with sage. However, I'm having trouble getting my solutions into an equation form. The integral expression is easy. I can do

from sage.symbolic.integration.integral import definite_integral
from sage.symbolic.integration.integral import indefinite_integral
x=var('x')
n=var('n')
assume(n,'integer')
assume(n!=0)
c=(1/(2*pi))*definite_integral(e^(-I*n*x),x,pi/2,pi)
c.full_simplify()

However, I don't know how to represent the piecewise part so I can check it with

bool(c==...)

Is there a way to do this with sage piecewise definitions? Something else?

One thought is that I could check the cases separately. That is, first check the n=1,5,... case etc. However, I'm not sure how to restrict n to be this. I can restrict it to be integer, or odd but I'm not sure about this.

Also, please forgive the horrendous math formatting. I wasn't able to get my latex formatted correctly here and I don't have enough rep to post a picture.