Pages

Tuesday, 15 November 2011

Straight Line Fit Using Least Squares Estimate

 #include<stdio.h>  
 #include<math.h>  
   
 void main()  
 {  
       float x[100],y[100],xy[100],xsquare[100],m,sumx,sumy,sumxy,sumxsq,a,b;  
         
       int i,j,k;  
   
   
       sumx=sumy=sumxy=sumxsq=0;  
       printf("\n\t\t\tLeast Square Method To Fit A Staright Line");  
       printf("\n=========================================================================================================================\n");  
       printf("\t\t\tEnter the value of m(number of terms) ");  
       scanf("%f",&m);  
       printf("\n=========================================================================================================================\n");  
       printf("\t\t\tEnter all the value of X \n");  
       for(i=0;i<m;i++)  
       {  
             printf("\tx[%d]=",i);  
             scanf("%f",&x[i]);  
             xsquare[i]=x[i]*x[i];//xsquare being calculated here  
             sumx=sumx+x[i];//summation of x  
             sumxsq=sumxsq+xsquare[i];//summation of x square calculated  
       }  
       printf("\n=========================================================================================================================\n");  
       printf("\t\t\tEnter all the value of Y \n");  
       for(i=0;i<m;i++)  
       {  
             printf("\ty[%d]=",i);  
             scanf("%f",&y[i]);  
             xy[i]=x[i]*y[i];//x*y being calculated  
             sumy=sumy+y[i];// summation of Y calculated  
             sumxy=sumxy+xy[i];//summation of XY calculated  
       }  
       a=((sumy*sumxsq)-(sumx*sumxy))/((m*sumxsq)-(sumx*sumx));  
       b=((m*sumxy)-(sumx*sumy))/((m*sumxsq)-(sumx*sumx));  
       printf("\n=========================================================================================================================\n\n");  
         
       printf("\t\t\tValue of a=%4.3f\tvalue of b=%4.3f\n",a,b);  
         
       printf("\n\t\t\tThus equation will be y=%4.3f + %4.3fx\n\n",a,b);  
         
       getchar();  
 }