Converting Mathematica Fourier series code to Python

Converting Mathematica Fourier series code to Python

Problem Description:

I have some simple Mathematica code that I’m struggling to convert to Python and could use some help:

a = ((-1)^(n))*4/(Pi*(2 n + 1));
f = a*Cos[(2 n + 1)*t];
sum = Sum[f, {n, 0, 10}];

Plot[sum, {t, -2 [Pi], 2 [Pi]}]

The plot looks like this:

enter image description here

For context, I have a function f(t):

enter image description here

I need to plot the sum of the first 10 terms. In Mathematica this was pretty straighforward, but for some reason I just can’t seem to figure out how to make it work in Python. I’ve tried defining a function a(n), but when I try to set f(t) equal to the sum using my list of odd numbers, it doesn’t work because t is not defined, but t is a variable. Any help would be much appreciated.

Below is a sample of one of the many different things I’ve tried. I know that it’s not quite right in terms of getting the parity of the terms to alternate, but more important I just want to figure out how to get ‘f’ to be the sum of the first 10 terms of the summation:

n = list(range(1,20,2))
def a(n):
   return ((-1)**(n))*4/(np.pi*n)
f = 0
for i in n:
   f += a(i)*np.cos(i*t)

Solution – 1

modifying your code, look the part which are different, mostly the mistake was in the part which you are not calculating based on n 0-10 :

n = np.arange(0,10)
t = np.linspace(-2 * np.pi, 2 *np.pi, 10000)
def a(n):
    return ((-1)**(n))*4/(np.pi*(2*n+1))
f = 0
for i in n:
    f += a(i)*np.cos((2*i +1) * t)

enter image description here

however you could write you could in matrix form, and avoid looping, using the vector and broadcasting:

n = np.arange(10)[:,None]
t = np.linspace(-2 * np.pi, 2 *np.pi, 10000)[:,None]
a = ((-1) ** n) * 4 / (np.pi*(2*n + 1))
f = (a * np.cos((2 * n + 1) * t.T )).sum(axis=0)
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.