温馨提示×

python中如何写一个线性函数

九三
858
2021-02-20 19:03:09
栏目: 编程语言

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中如何写一个线性函数

0