原文地址:http://wiki.klniu.com/zh-hans/Python/Modules/Scipy
import numpy as np from scipy.optimize import leastsq import pylab as pl x = np.arange(1, 17, 1) y = np.array([4.00, 6.40, 8.00, 8.80, 9.22, 9.50, 9.70, 9.86, 10.00, 10.20, 10.32, 10.42, 10.50, 10.55, 10.58, 10.60]) #第一个拟合,*度为3 z1 = np.polyfit(x, y, 3) # 生成多项式对象 p1 = np.poly1d(z1) print(z1) print(p1) # 第二个拟合,*度为6 z2 = np.polyfit(x, y, 6)
# 生成多项式对象
p2
= np.
poly1d
(z2
)
print
(z2
)
print
(p2
)
# 绘制曲线
# 原曲线pl.
plot
(x
, y
,
'b^-'
, label
=
'Origin Line'
)pl.
plot
(x
, p1
(x
)
,
'gv--'
, label
=
'Poly Fitting Line(deg=3)'
)pl.
plot
(x
, p2
(x
)
,
'r*'
, label
=
'Poly Fitting Line(deg=6)'
)pl.
axis
(
[
0
,
18
,
0
,
18
]
)pl.
legend
(
)
# Save figurepl.
savefig
(
'scipy02.png'
, dpi
=
96
)
输出结果:
[ 0.00624491 -0.20371114 2.18193147 2.57208791] 3 2 0.006245 x - 0.2037 x + 2.182 x + 2.572 [ -1.89843481e-06 1.90557772e-04 -6.80682074e-03 1.16832830e-01 -1.04793542e+00 4.90253564e+00 1.76057692e-02] 6 5 4 3 2 -1.898e-06 x + 0.0001906 x - 0.006807 x + 0.1168 x - 1.048 x + 4.903 x + 0.01761
图像: