C#最小二乘法直线拟合算法

測試數據:

x 2 3 4 5 6
y 0.22 0.38 0.55 0.65 0.70
Terminal(粗體為輸出,其它為輸入):
請輸入樣本點的數目:5
請輸入樣本點的坐標。
x,y=
2,0.22
x,y=3,0.38
x,y=4,0.55
x,y=5,0.65
x,y=6,0.70
x_bar=4
y_bar=0.5
sigma(xi*yi)=11.23
n*x_bar*y_bar=10
sigma(xi*xi)=90
n*x_bar*x_bar=80
b=(sigma(xi*yi)-n*x_bar*y_bar)/(sigma(xi*xi)-n*x_bar*x_bar)=(11.23-10)/(90-80)
=0.123
a=y_bar-b*x_bar=0.5-0.123*4=0.008
直綫方程:y=0.123x+0.008


Source Code:
#include

int main () {
double tx,ty;
double sigma_xy=0;
double sigma_xx=0;
int counter;
double sum_x=0;
double sum_y=0;
int n=0;
INPUT:
printf("請輸入樣本點的數目:");
if (scanf("%d",&counter)!=1) {
printf("格式錯誤。\n");
goto INPUT;
} else if (counter<2) {
printf("樣本點數目不能小於2。\n");
goto INPUT;
}
printf("請輸入樣本點的坐標。\n");

while (n printf("x,y=");
if ((scanf("%lf,%lf",&tx,&ty)!=2)) {
printf("格式輸入錯誤,請重新輸入。\n");
continue;
}
n++;
sigma_xy+=tx*ty;
sigma_xx+=tx*tx;
sum_x+=tx;
sum_y+=ty;

}

double x_bar=sum_x/((double)counter);
double y_bar=sum_y/((double)counter);
double nxy_bar=((double)counter)*x_bar*y_bar;
double nxx=((double)counter)*x_bar*x_bar;
printf("x_bar=%g\n",x_bar);
printf("y_bar=%g\n",y_bar);
printf("sigma(xi*yi)=%g\n",sigma_xy);
printf("n*x_bar*y_bar=%g\n",nxy_bar);
printf("sigma(xi*xi)=%g\n",sigma_xx);
printf("n*x_bar*x_bar=%g\n",nxx);
printf("b=(sigma(xi*yi)-n*x_bar*y_bar)/(sigma(xi*xi)-n*x_bar*x_bar)=(%g-%g)/(%g-%g)\n",sigma_xy,nxy_bar,sigma_xx,nxx);
double b=(sigma_xy-nxy_bar)/(sigma_xx-nxx);
printf(" =%g\n",b);
double a=y_bar-b*x_bar;
printf("a=y_bar-b*x_bar=%g-%g*%g=%g\n",y_bar,b,x_bar,a);

if (a>0) {
printf("直綫方程:y=%gx+%g\n",b,a);
} else if (a==0) {
printf("直綫方程:y=%gx\n",b);
} else {
printf("直綫方程:y=%gx%g\n",b,a);
}
return 0;
}

转自:

http://equinox1993.blog.163.com/blog/static/32205137201091611386204/

你可能感兴趣的:(c#编程)