Demo entry 6658044

home_work

   

Submitted by anonymous on Nov 06, 2017 at 03:15
Language: Python. Code size: 2.4 kB.

#############################################################
#			   HOME WORK                        #
#                                                           #	
#	members:                                            #
#		FISLI Haythem                               #
#		HAMDANE Djaafer                             #
#		BOUALI Abdennour                            #
#			                                    #
#	Section : 01			groupe : 02         #
#                                                           #
#############################################################



import numpy as np
from scipy.integrate import quad
import matplotlib.pyplot as plt

""" precision """
depth = 100

""" filename """
filename = "Example.pdf"

""" interval """
L = 5
""" period """
T = 2

A = 1
""" square wave function """
def u(x):
	if x >= 0:
		if int(x % 2) == 0:
			return A
		else :
			return -A
	else:
		if int(-x +1) % 2 == 0:
			return A
		else :
			return -A

""" compute u(x) """
y = [u(x) for x in np.arange(-L,L,0.01)]

""" number of points """
x = np.linspace(-L,L,1000)

""" an coefficients """ 
a = range(0,depth+1)
""" bn coefficients """
b = range(0,depth+1)
     

""" return sin(n*w*x) with replacing n by its value """ 
def sine(k): return lambda x: (2/T)*np.sin(k*2*np.pi/T*x)
 
""" return cos(n*w*x) with replacing n by its value """ 
def cosine(k): return lambda x: (2/T)*np.cos(k*2*np.pi/T*x)
 
 
""" return expression of multiplication of two functions 
	Ex : u(x) * sin(n*w*x)
"""
def mult(u,v): return lambda x: u(x)*v(x)
 
""" compute a[0] """
a[0] = 1/T * quad(u ,0,T)[0]

# -- compute an and bn --
for k in range(1,depth+1):
    a[k] = quad(mult(u,cosine(k)) ,0,T)[0]
 
for k in range(1,depth+1):
    b[k] = quad(mult(u,sine(k)),0,T)[0]
     
# -- define the approximate function -- 
def fourier_approx(x):
    value = a[0]
    for k in range(1,depth+1,1):
        value = value + a[k]*cosine(k)(x) + b[k]*sine(k)(x)
        
    return(value)   
 
# -- plot the original function and the Fourier approximate --
x_values = np.arange(-L,L,0.001)
 
plt.plot(x_values, fourier_approx(x_values),label="FS (depth %r)" %depth)
plt.plot(x, y,label=r"$u(x)$")
 
plt.legend(loc="upper left")
plt.ylim(-2.5,2.5)
#plt.savefig("fig-100")
plt.show()

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).