Python线性拟合实现函数与用法示例

作者:hellBaron 时间:2023-12-04 14:29:33 

本文实例讲述了Python线性拟合实现函数与用法。分享给大家供大家参考,具体如下:

1. 参考别人写的:


#-*- coding:utf-8 -*-
import math
import matplotlib.pyplot as plt
def linefit(x , y):
 N = float(len(x))
 sx,sy,sxx,syy,sxy=0,0,0,0,0
 for i in range(0,int(N)):
   sx += x[i]
   sy += y[i]
   sxx += x[i]*x[i]
   syy += y[i]*y[i]
   sxy += x[i]*y[i]
 a = (sy*sx/N -sxy)/( sx*sx/N -sxx)
 b = (sy - a*sx)/N
 r = abs(sy*sx/N-sxy)/math.sqrt((sxx-sx*sx/N)*(syy-sy*sy/N))
 return a,b,r
if __name__ == '__main__':
 x=[ 1 ,2 ,3 ,4 ,5 ,6]
 y=[ 2.5 ,3.51 ,4.45 ,5.52 ,6.47 ,7.51]
 a,b,r=linefit(x,y)
 print("X=",x)
 print("Y=",y)
 print("拟合结果: y = %10.5f x + %10.5f , r=%10.5f" % (a,b,r) )
 plt.plot(x, y, "r:", linewidth=2)
 plt.grid(True)
 plt.show()

显示图像如下:

Python线性拟合实现函数与用法示例

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


#-*- coding:utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import math
f = lambda x:5*x+4
tx = np.linspace(0,10,50)
print tx
plt.plot(tx, f(tx), "r-", linewidth=2)
plt.grid(True)
plt.show()

运行结果:

Python线性拟合实现函数与用法示例

PS:这里再为大家推荐两款相似的在线工具供大家参考:

在线多项式曲线及曲线函数拟合工具:
http://tools.jb51.net/jisuanqi/create_fun

在线绘制多项式/函数曲线图形工具:
http://tools.jb51.net/jisuanqi/fun_draw

希望本文所述对大家Python程序设计有所帮助。

来源:https://blog.csdn.net/way88liu/article/details/77853881

标签:Python,线性拟合
0
投稿

猜你喜欢

  • MySQL错误中文参照列表

    2010-09-30 14:41:00
  • pycharm中使用request和Pytest进行接口测试的方法

    2022-06-30 03:34:46
  • GoLang并发机制探究goroutine原理详细讲解

    2023-08-30 05:41:33
  • java使用mysql预编译语句查询优势及示例详解

    2024-01-13 21:15:00
  • python实现求纯色彩图像的边框

    2022-04-01 22:04:51
  • perl用变量做句柄介绍

    2022-12-18 22:19:01
  • Python中的X[:,0]、X[:,1]、X[:,:,0]、X[:,:,1]、X[:,m:n]和X[:,:,m:n]

    2023-03-13 09:20:52
  • textarea 在IE和FF下换行无法正常显示的解决方法

    2022-09-11 01:33:40
  • Python scikit-learn 做线性回归的示例代码

    2022-05-03 11:00:54
  • Django与遗留的数据库整合的方法指南

    2024-01-15 02:20:32
  • php之php.ini配置文件讲解案例

    2023-06-11 18:19:06
  • Python中fnmatch模块的使用详情

    2021-06-14 20:50:18
  • python学生管理系统开发

    2022-05-20 23:00:00
  • Python编程基础之构造方法和析构方法详解

    2022-02-26 02:38:03
  • css把超出的部分显示为省略号的方法兼容火狐

    2010-10-07 09:02:44
  • 利用Python实现在同一网络中的本地文件共享方法

    2023-10-31 00:41:58
  • 20行Python代码实现一款永久免费PDF编辑工具

    2023-11-17 23:51:45
  • 基于Python实现RLE格式分割标注文件的格式转换

    2022-10-22 08:41:12
  • Yii2框架整合Xunsearch搜索引擎的方法

    2024-06-05 09:37:48
  • Python关于维卷积的理解

    2022-06-05 07:26:21
  • asp之家 网络编程 m.aspxhome.com