python线性拟合代码和函数


  • 1
[python]  view plain  copy
  1. #-*- coding:utf-8 -*-  
  2. import math  
  3. import matplotlib.pyplot as plt  
  4. def linefit(x , y):  
  5.     N = float(len(x))  
  6.     sx,sy,sxx,syy,sxy=0,0,0,0,0  
  7.     for i in range(0,int(N)):  
  8.         sx  += x[i]  
  9.         sy  += y[i]  
  10.         sxx += x[i]*x[i]  
  11.         syy += y[i]*y[i]  
  12.         sxy += x[i]*y[i]  
  13.     a = (sy*sx/N -sxy)/( sx*sx/N -sxx)  
  14.     b = (sy - a*sx)/N  
  15.     r = abs(sy*sx/N-sxy)/math.sqrt((sxx-sx*sx/N)*(syy-sy*sy/N))  
  16.     return a,b,r  
  17.   
  18. if __name__ == '__main__':  
  19.     x=[ 1 ,2  ,3 ,4 ,5 ,6]  
  20.     y=[ 2.5 ,3.51 ,4.45 ,5.52 ,6.47 ,7.51]  
  21.   
  22.     a,b,r=linefit(x,y)  
  23.   
  24.     print("X=",x)  
  25.     print("Y=",y)  
  26.     print("拟合结果: y = %10.5f x + %10.5f , r=%10.5f" % (a,b,r) )  
  27.   
  28.     plt.plot(x, y, "r:", linewidth=2)  
  29.     plt.grid(True)  
  30.     plt.show()  



显示图像如下:


2

不用拟合,直接显示一个一元函数

[python]  view plain  copy
  1. #-*- coding:utf-8 -*-  
  2. import numpy as np  
  3. import matplotlib.pyplot as plt  
  4. import math  
  5.   
  6. f = lambda x:5*x+4  
  7. tx = np.linspace(0,10,50)  
  8. print tx  
  9.   
  10. plt.plot(tx, f(tx), "r-", linewidth=2)  
  11. plt.grid(True)  
  12. plt.show()  

猜你喜欢

转载自blog.csdn.net/henusyb/article/details/79836455