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

yipeiwu_com6年前Python基础

如下所示:

from numpy import *
import numpy as np
import matplotlib.pyplot as plt

plt.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.0
X2Sum = 0.0
X3Sum = 0.0
X4Sum = 0.0
ISum = 0.0
YSum = 0.0
XYSum = 0.0
X2YSum = 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**2
plt.plot(x,y)
show_line = "y="+str(a)+"+("+str(b)+"x)"+"+("+str(c)+"x2)";
plt.title(show_line)
plt.show()

以上这篇Python实现二维曲线拟合的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python3+requests接口自动化session操作方法

在进行接口自动化测试时,有好多接口都基于登陆接口的响应值来关联进行操作的,在次之前试了很多方法,都没有成功,其实很简单用session来做。 1、在登陆接口创建一个全局session...

pip matplotlib报错equired packages can not be built解决

pip安装matplotlib 在centos6.5 64bit上用pip安装matplotlib时候报错: * The following required packages ca...

Python实现计算最小编辑距离

Python实现计算最小编辑距离

最小编辑距离或莱文斯坦距离(Levenshtein),指由字符串A转化为字符串B的最小编辑次数。允许的编辑操作有:删除,插入,替换。具体内容可参见:维基百科—莱文斯坦距离。一般代码实现的...

Python中列表、字典、元组、集合数据结构整理

本文详细归纳整理了Python中列表、字典、元组、集合数据结构。分享给大家供大家参考。具体分析如下: 列表:复制代码 代码如下:shoplist = ['apple', 'mango',...

浅谈python jieba分词模块的基本用法

jieba(结巴)是一个强大的分词库,完美支持中文分词,本文对其基本用法做一个简要总结。 特点 支持三种分词模式: 精确模式,试图将句子最精确地切开,适合文本分析;...