/*least
square fitting of a straight line */
#include<stdio.h>
#include<math.h>
void
main()
{
int n,i;
float
a,b,x[20],y[20],sx=0.0,sxx=0.0,sy=0.0,sxy=0.0;
printf("enter
the total number of data:");
scanf("%d",&n);
printf("enter
the value of x:");
for(i=0;i<n;i++)
{
scanf("%f",&x[i]);
}
printf("enter
the values of y:");
for(i=0;i<n;i++)
{
scanf("%f",&y[i]);
}
for(i=0;i<n;i++)
{
sx=sx+x[i];
sxx=sxx+(x[i]*x[i]);
sy=sy+y[i];
sxy=sxy+(x[i]*y[i]);
}
a=(n*sxy-sx*sy)/(n*sxx-sx*sx);
b=(sxx*sy-sx*sxy)/(n*sxx-sx*sx);
printf("the
line of least fit is:\n y=%fx+%f\n",a,b);
}
Result:
enter the
total number of data:5
enter the
value of x:1 2 3 4 5
enter the
values of y:2.03 4.26 6.59 8.12 10.28
the line of
least fit is:
y=2.036000x+0.148000
Press any
key to continue
No comments:
Post a Comment
Thanks for comment.