使用Python拟合函数曲线需要用到一些第三方库:
numpy:科学计算的基础库(例如:矩阵)
matplotlib:绘图库
scipy:科学计算库
如果没有安装过这些库,需要在命令行中输入下列代码进行安装:
pip install numpy matplotlib scipy
拟合多项式
'''
Author: CloudSir
Date: 2021-08-01 13:40:50
LastEditTime: 2021-08-02 09:41:54
LastEditors: CloudSir
Description: Python拟合多项式
https://github.com/cloudsir
'''
import matplotlib.pyplot as plt
import numpy as np
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [2.83, 9.53, 14.52, 21.57, 38.26, 53.92, 73.15, 101.56, 129.54, 169.75, 207.59]
z1 = np.polyfit(x, y, 3) #用3次多项式拟合,输出系数从高到0
p1 = np.poly1d(z1) #使用次数合成多项式
y_pre = p1(x)
plt.plot(x,y,'.')
plt.plot(x,y_pre)
plt.show()