機器學習准備---3、模擬e^x的麥克勞林展開式
一、總結
一句話總結:
1、用麥克勞林展開式模擬函數,比如e^x,階數越高就越接近
2、e^x=f(0)+ f′(0)x+ f″(0)x ²/ 2!+...+ fⁿ(0)x^n/n!+Rn(x)=1+x+x^2/2!+x^3/3!+...+x^n/n!+Rn(x)
3、畫圖的時候,求y就是算上前n項
y = consY(i,x) # y值函數 def consY(n,x): y = 1 for i in range(1,n): y += x**i/factorial(i) return y
二、使用matplotlib模擬e^x的麥克勞林展開式
轉自或參考:使用matplotlib模擬e^x的麥克勞林展開式
https://www.cnblogs.com/thsk/p/8330009.html
使用matplotlib模擬下e^x的麥克勞林展開式,用plt畫圖
import matplotlib.pyplot as plt import numpy as np import random ''' e^x的麥克勞林展開式: e^x= f(0)+ f′(0)x+ f″(0)x ²/ 2!+...+ fⁿ(0)x^n/n!+Rn(x) =1+x+x^2/2!+x^3/3!+...+x^n/n!+Rn(x) ''' # 階乘函數 def factorial(n): x = 1 for i in range(1,n+1): x = x * i return x # y值函數 def consY(n,x): y = 1 for i in range(1,n): y += x**i/factorial(i) return y # 生成圖像 def moniPlot(n,x): # 定義一個顏色集合 colors = ['g','b','black','cyan','lightgreen','yellow','deeppink','darkorchid'] plt.figure() # 原函數 y = np.e**x # 畫原函數圖像並進行標記 plt.plot(x,y,'r-',linewidth=2,label='e^x') # 麥克勞林展開添加到圖像上 for i in range(2,n): y = consY(i,x) # 隨機選擇顏色 color = colors[random.randint(0,len(colors)-1)] linestyle = '--' # 畫圖像,並對最后一個進行標記 if i == n: plt.plot(x,y,color=color,linewidth=1,linestyle=linestyle,label="nearly e^x") else: plt.plot(x,y,color=color,linewidth=1,linestyle=linestyle) plt.plot(x,y,color=color,linewidth=1,linestyle=linestyle) #添加注釋 plt.text(1.2, consY(10,3.9),"Maclaurin's series of e^x ",size=12) # 將標記繪制圖例,位置為於中間左側 plt.legend(['e^x',"nearly e^x"], loc = 'center left') plt.show() # 定義 x , y x = np.linspace(1,4,80) # 原函數 # y = np.e**x # Maclaurin展開 3項 # y1 = consY(2,x) # 展開 4項 # y2 = consY(3,x) # tylor 5項 # y3 = consY(4,x) # 調用生成圖像 moniPlot(10,x) # 關閉圖 plt.close()
運行代碼,plt展示的結果如下(展開式的項數越多,越接近原函數):