Linux 拨号vps windows公众号手机端

python中如何写一个线性函数

lewis 6年前 (2019-04-10) 阅读数 9 #程序编程
文章标签 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() #添加网格线


效果图:

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门