Computer-based numerical and statistical techniques
Ex: Find the line of best fit for the following data:
x
|
1
|
2
|
3
|
4
|
5
|
y
|
4
|
6
|
3
|
5
|
7
|
Solution:
x
|
y
|
xy
|
x2
|
1
2
3
4
5
|
4
6
3
5
7
|
4
12
9
20
35
|
1
4
9
16
25
|
15
|
25
|
80
|
55
|
Here ∑xi= 15 ∑yi=25 ∑xiyi= 80 ∑xi2= 55
Substituting the values from the table into the system below:
we get 5A +15B= 25
15A+ 55B=80
Solve both equations using Cramer’s rule: a= 3.5 b= 0.5
hence the equation to curve-fit the data with a straight line is:
y= 3.5 + 0.5x
Note: Cramer Formula to solve two linear equation
a1x+b1y=c1
a2x+b2y=c2
here x=(c1*b2-b1*c2)/(a1*b2-b1*a2)
y=(a1*c2-c1*a2)/ (a1*b2-b1*a2)
C Program :
#include<stdio.h>
void main()
{ int i;
float n,a,b,x[10],y[10],xy[10],x2[10],y2[10],sumx=0,sumy=0,sumxy=0, sumx2=0;
printf("\nenter the no of n points");
scanf("%f",&n);
for(i=1;i<=n;i++)
{ printf("\nenter value of x%d",i);
scanf("%f",&x[i]);
printf("\nenter value of y%d",i);
scanf("%f",&y[i]);
}
for(i=1;i<=n;i++)
{ xy[i]=x[i]*y[i];
x2[i]=x[i]*x[i];
}
for(i=1;i<=n;i++)
{ sumxy=sumxy+xy[i];
sumx2=sumx2+x2[i];
sumx=sumx+x[i];
sumy=sumy+y[i];
}
printf("\nx\ty\txy\tx2");
printf("\n*******************************");
for(i=1;i<=n;i++)
{printf("\n%.2f\t%.2f\t%.2f\t%.2f",x[i],y[i],xy[i],x2[i]);
}
printf("\n********************************");
printf("\n%.2f\t%.2f\t%.2f\t%.2f",sumx,sumy,sumxy,sumx2);
printf("\n********************************");
printf("\n\n\nNomal Equations are:");
printf("\n**********************");
printf("\n\t%.2fA+%.2fB=%.2f",n,sumx,sumy);
printf("\n\t%.2fA+%.2fB=%.2f",sumx,sumx2,sumxy);
a=(sumy*sumx2-sumx*sumxy)/(n*sumx2-sumx*sumx);
b=(n*sumxy-sumy*sumx)/(n*sumx2-sumx*sumx);
printf("\n\na=%.2f and b=%.2f",a,b);
printf("\n\nHence equation of straight line is:y=%.2f+%.2fx",a,b);
}
Output:
enter the no of n points 5
enter a value of x1 1
enter a value of y1 4
enter a value of x2 2
enter a value of y2 6
enter value of x3 3
enter value of y3 3
enter value of x4 4
enter value of y4 5
enter value of x5 5
enter value of y5 7
x y xy x2
*******************************
1.00 4.00 4.00 1.00
2.00 6.00 12.00 4.00
3.00 3.00 9.00 9.00
4.00 5.00 20.00 16.00
5.00 7.00 35.00 25.00
********************************
15.00 25.00 80.00 55.00
********************************
Nomal Equations are:
**********************
5.00A+15.00B=25.00
15.00A+55.00B=80.00
a=3.50 and b=0.50
Hence equation of the straight line is:y=3.50+0.50x
No comments:
Post a Comment