2017-10-10 68 views
0
x=1 
n=1 
series1=0 
z=[] 
t= arange(-2,2,.1) 
for i in t: 
    series1=series1 + ((2/n/pi)*(sin(n*x))) 
    x+=1 
    z.append(series1) 

my_list=z 
newlist = [x+.5 for x in my_list] 


plot(newlist,t) 
xlabel('x-range') 
ylabel('A(X)') 
title('square wave') 

的形象代表,我試圖繪製功能的方波(蟒蛇): 我的代碼沒有密謀利用傅立葉級數

我的繪圖表,這看起來並不像一個方波:

回答

1

編輯:

更Python版本:

import matplotlib.pyplot as plt 
import numpy as np 

N_max = 101 #the larger the value the steeper the transition from 0 to 1 and the more "square" 
n_odds = np.arange(1,N_max,2) 
xs = np.arange(-6,6,0.1) 
ys = [0.5+sum(np.multiply(2/(n_odds*np.pi), np.sin(n_odds*x))) for x in xs] 

plt.plot(xs, ys) 
plt.show() 

這是一個適合我的版本。你最大的錯誤是沒有騎單車穿過奇怪的N。如果您對代碼有任何疑問,請留下評論。

import matplotlib.pyplot as plt 
import numpy as np 

N_max = 101 
n_odds = np.arange(1,N_max,2) 
xs = np.arange(-6,6,0.1) 
ys = [] 
for x in xs: 
    sum_terms = [] 
    for n_odd in n_odds: 
     frac_term = 2/(n_odd*np.pi) 
     sin_term = np.sin(n_odd*x) 
     sum_term = frac_term*sin_term 
     sum_terms.append(sum_term) 

    y = 0.5+sum(sum_terms) 
    ys.append(y) 

plt.plot(xs, ys) 
plt.show() 

enter image description here