[英]Algorithm to detect a linear part of a data set
您可以从使用 x 和 y 值确定两个点的斜率开始。
说点1和2,斜率= 2。然后计算点2和3的斜率。如果后者的斜率与前者不同,那么你知道它不是线性的。
只需对整个数据集执行 for 循环并将当前值与下一个值进行比较即可获得斜率。
from decimal import Decimal
def linear_equation(p1,p2):
#points are arrays like p=(x,y)
m=slope(p1,p2) #slope
c=(p2[1]-(m*p2[0])) #y-intercept of line
return 'y='+str(m)+ 'x' +'+' +str(c)
def slope(p1,p2):
return Decimal((p2[1]-p1[1]))/Decimal(p2[0]-p1[0])
points =[[0,0],[1,1],[2,2],[3,4],[4,5],[5,6],[7,30],[8,35],[9,39]]
for p in range(0,len(points)-2):
#if the slopes of points (a,b) and (b,c) are the same then print the equation
#you could really omit the if statment if you just want to calculate the
#equations for each set of points and do the comparasons later.
#change the for condition to -1 instead of -2 if this is the case.
if slope(points[p],points[p+1]) == slope(points[p+1],points[p+2]):
print(str(lin_equ(points[p],points[p+1])))
else:
print("Non-Linear")
输出:
y=1x+0
非线性
非线性
y=1x+1
非线性
非线性
非线性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.