本文記錄利用numpy.polyfit實現多項式係數的擬合以及利用numpy.polyder實現求導,並通過numpy.poly1d將係數轉換為多項式函數。
示例代碼如下:
import numpy as np
import matplotlib.pyplot as plt
xs = np.linspace(0,1,31)
ys = np.sin(xs*np.pi*3)
# ys = xs**2+0.5
fit_fn_arg = np.polyfit(xs,ys,10) ### 擬合出來的多項式係數 最高次數為10
df = np.polyder(fit_fn_arg) ### 多項式求導後的係數
df2 = np.polyder(df)
fit_fn = np.poly1d(fit_fn_arg)
print(fit_fn_arg,fit_fn_arg.shape)
print(df)
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
ax1.scatter(xs,ys,label="original data",c="red")
ax1.plot(xs,fit_fn(xs),label="fit data")
ax2.plot(xs,np.poly1d(df)(xs),label="1 st derivatives")
ax2.plot(xs,np.poly1d(df2)(xs),label="2 st derivatives")
ax1.legend()
ax2.legend()
plt.show()代碼運行結果如下,擬合了1、2階的導數: