0

I am writing code for summing the Fourier Series that ranges from [-n,n]. However, I'm having trouble with it iterating when it gets to n = 0. I wrote an 'if' statement inside my while loop so it can ignore it, but it seems like it isn't. Here's my code:

from __future__ import division
import numpy as np
import math
import matplotlib.pyplot as plt


#initial values 
ni = -10
nf = 10
ti = -3
tf = 3
dt = 0.01
yi = 0 #initial f(t) value
j = complex(0,1)

#initialization
tarray = [ti]
yarray = [yi]
t = ti
n = ni
y = yi


cn = 1/(8*(np.pi)**3*n**3*j**3)*(j*4*np.pi*n) #part (b)


#iterating loop
while t<tf:
    n = ni 
    y = yi 
    while n<nf:
        if n == 0: 
            cn = 1/6
            y += cn
            n += 1
        else: 
            y +=  cn*np.exp(j*np.pi*n*t)  
            n += 1

    yarray.append(y)
    t+=dt
    tarray.append(t)

#converting list-array
tarray = np.array(tarray)
yarray = np.array(yarray)

#plotting
plt.plot(tarray,yarray, linewidth = 1)
plt.axis("tight")
plt.xlabel('t')
plt.ylabel('f(t) upto n partial sums')
plt.title('Fourier Series for n terms')
plt.legend()
plt.show()

I want it to iterate and create an array of y-values for n ranging from some negative number to some positive number (say for n from [-10,10]), but as soon as it hits n = 0 it seems to be plugging that in into the 'else' clause even though I want it to use what's in the 'if' clause, giving me a "ZeroDivisionError: complex division by zero". How do I fix this?

Edit: Put the entire code block here so you can see the context.

Paul R
  • 208,748
  • 37
  • 389
  • 560
ShinyPebble
  • 135
  • 1
  • 1
  • 10

2 Answers2

0

This is not the most elegant way at all but try this:

while t<tf:
n = ni 
y = yi 
while n<nf:
    try:
        1/n
        cn = 1/6
        y += cn
        n += 1

     except ZeroDivisionError: 
        y +=  cn*np.exp(j*np.pi*n*t)  #1/n*np.sin(n*t)
        n += 1

yarray.append(y)
t+=dt
tarray.append(t)
0

The coefficient cn is a function of n and should be updated in every loop. You made it constant (and even equal to 1/6 for positive n).

The inner loop could look like

y = 1/6                                        # starting with n = 0
for n in range(1,nf):
    y -= 1/(2*np.pi*n)**2 * np.sin(np.pi*n*t)   # see below

Corresponding coefficients for positive and negative n's are equal and exp(ix) - exp(-ix) = 2i sin(x), so it nicely reduces. (Double check the calculation.)

ptrj
  • 5,152
  • 18
  • 31