python中怎么写一个线性函数
python中怎样写一个线性函数
在python中书写一个线性函数,具体方法以下:
def temp1(datas):
x = datas[0] #获得自变量x
y = datas[1] #获得因变量y
n = np.size(answer1, axis = 1) #获得有多少个自变量,axis=1代表获得矩阵的列数
#根据公式计算k
k = (n*np.sum(x*y) - np.sum(x)*np.sum(y)) / (n*np.sum(np.power(x,2)) - np.sum(x) * np.sum(x))
#根据公式计算b
b = (np.sum(np.power(x,2)) * np.sum(y) -np.sum(x) * np.sum(x*y)) / (n*np.sum(np.power(x,2)) - np.sum(x) * np.sum(x))
las = k*x + b #根据公式得到拟合函数
fig = plt.figure() #取得figure对象
ax1 = fig.add_subplot(1,1,1) #添加一个图纸
ax1.set_xlim([min(x)-0.5, max(x)+0.5]) #设置x轴刻度
ax1.set_ylim([min(y) -0.5, max(y) +0.5]) #设置y轴刻度
plt.plot(x,las,'k',label='拟合函数') #画出拟合函数
plt.plot(x,y,'o',label = '样本数据') #画出样本数据
plt.grid() #添加网格线
效果图:
文章来源:丸子建站
文章标题:python中怎么写一个线性函数
https://www.wanzijz.com/view/4414.html