首页 > 编程 > Python > 正文

Python实现二维曲线拟合的方法

2020-01-04 13:39:42
字体:
来源:转载
供稿:网友

如下所示:

from numpy import *import numpy as npimport matplotlib.pyplot as pltplt.close()fig=plt.figure()plt.grid(True)plt.axis([0,10,0,8])#列出数据point=[[1,2],[2,3],[3,6],[4,7],[6,5],[7,3],[8,2]]plt.xlabel("X")plt.ylabel("Y")#用于求出矩阵中各点的值XSum = 0.0X2Sum = 0.0X3Sum = 0.0X4Sum = 0.0ISum = 0.0YSum = 0.0XYSum = 0.0X2YSum = 0.0#列出各点的位置for i in range(0,len(point)): xi=point[i][0] yi=point[i][1] plt.scatter(xi,yi,color="red") show_point = "("+ str(xi) +","+ str(yi) + ")" plt.text(xi,yi,show_point) XSum = XSum+xi X2Sum = X2Sum+xi**2 X3Sum = X3Sum + xi**3 X4Sum = X4Sum + xi**4 ISum = ISum+1 YSum = YSum+yi XYSum = XYSum+xi*yi X2YSum = X2YSum + xi**2*yi# 进行矩阵运算# _mat1 设为 mat1 的逆矩阵m1=[[ISum,XSum, X2Sum],[XSum, X2Sum, X3Sum],[X2Sum, X3Sum, X4Sum]]mat1 = np.matrix(m1)m2=[[YSum], [XYSum], [X2YSum]]mat2 = np.matrix(m2)_mat1 =mat1.getI()mat3 = _mat1*mat2# 用list来提取矩阵数据m3=mat3.tolist()a = m3[0][0]b = m3[1][0]c = m3[2][0]# 绘制回归线x = np.linspace(0,10)y = a + b*x + c*x**2plt.plot(x,y)show_line = "y="+str(a)+"+("+str(b)+"x)"+"+("+str(c)+"x2)";plt.title(show_line)plt.show()

以上这篇Python实现二维曲线拟合的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持VEVB武林网。


注:相关教程知识阅读请移步到python教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表