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

yipeiwu_com6年前Python基础

本文实例讲述了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()

显示图像如下:

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()

运行结果:

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

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

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

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数学运算技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

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

相关文章

Python编程实现双链表,栈,队列及二叉树的方法示例

本文实例讲述了Python编程实现双链表,栈,队列及二叉树的方法。分享给大家供大家参考,具体如下: 1.双链表 class Node(object): def __init__(...

python turtle 绘制太极图的实例

python turtle 绘制太极图的实例

效果如下所示: # -*- coding: utf-8 -*- import turtle # 绘制太极图函数 def draw_TJT(R):    ...

python xlsxwriter创建excel图表的方法

python xlsxwriter创建excel图表的方法

本文实例为大家分享了python xlsxwriter创建excel图表的具体代码,供大家参考,具体内容如 #coding=utf-8 import xlsxwriter fro...

利用django如何解析用户上传的excel文件

前言 我们在工作中的时候,会有这种需求:用户上传一个格式固定excel表格到网站上,然后程序负债解析内容并进行处理。我最近在工作中就遇到了,所以想着将解决的过程总结分享出来,方便大家参考...

Python常用模块介绍

python除了关键字(keywords)和内置的类型和函数(builtins),更多的功能是通过libraries(即modules)来提供的。 常用的libraries(module...