Ask Your Question
0

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

asked 2020-06-04 06:54:46 +0100

matthuszagh gravatar image

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.

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2020-06-04 20:16:45 +0100

Juanjo gravatar image

You can define $f$ in terms of the Heaviside function and then integrate directly without any imports. Try this code:

f(x) = heaviside(x-pi/2)
def c(n):
    return integral(f(x)*exp(-I*n*x), (x,-pi,pi))
for n in range(0,40):
    show(html(f"$c_{{{n}}}={latex(c(n))}$"))
edit flag offensive delete link more

Comments

This does the trick, thanks! However, I wasn't able to get your show(...) code to run, i kept getting syntax errors: File "<ipython-input-23-b7fe66c04faf>", line 2 show(html(f"$c_{{{n}}}={latex(c(n))}$")) ^ SyntaxError: invalid syntax

(note the ^ lines up with the ending ")

matthuszagh gravatar imagematthuszagh ( 2020-06-04 21:36:42 +0100 )edit

The last line of code should work in a recent release of SageMath (9.0 or 9.1), as can be verified in this SageMath Cell. Are you still running version 8.9 or earlier? To check it, type version() and look at the ouput.

Juanjo gravatar imageJuanjo ( 2020-06-04 22:10:20 +0100 )edit

Ah that would explain it, I'm running 8.9.

matthuszagh gravatar imagematthuszagh ( 2020-06-04 22:40:34 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2020-06-04 06:50:52 +0100

Seen: 283 times

Last updated: Jun 04 '20