直线拟合(转贴)
Submitted by hubdog on Thu, 2008-12-04 13:41
- function FitLine(x,y: array of double;len: integer; var k,b,c: double):boolean;
- var
- i: integer;
- sx,sy,s2x,sxy:double;
- begin
- result:=true;
- if len<2 then //少于两点无法拟合
- begin
- result:=false;
- exit;
- end;
- sx:=0;
- sy:=0;
- s2x:=0;
- sxy:=0;
- for i:=0 to len-1 do
- begin
- sx:=sx+x[i];
- sy:=sy+y[i];
- s2x:=s2x+x[i]*x[i];
- sxy:=sxy+y[i]*x[i];
- end;
- if sx*sx-len*s2x=0 then
- c:=x[0]
- else
- begin
- c:=infinity;
- k:=(sy*sx-sxy*len)/(sx*sx-len*s2x);
- b:=(sy-k*sx)/len;
- end;
- end;