本文实例讲述了python线性拟合实现函数与用法。分享给大家供大家参考,具体如下:
1. 参考别人写的:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
#-*- 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. 不用拟合,直接显示一个一元函数
1
2
3
4
5
6
7
8
9
10
|
#-*- 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程序设计有所帮助。
原文链接:https://blog.csdn.net/way88liu/article/details/77853881