Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

ASSIGNMENT NO.

: 08
STATEMENT : Curve fitting using least square method
ALGORITHM :
Input: Taking data points of x and y axis from the user.
Output: Approximate value of x and c in form y=mx+c .
Steps:
1. START.
2. Declaring the float(a,b) and
integer(n,i,x[20],y[20],sumx=0,sumy=0,sumxy=0,sumx2=0[i
nitialised]) variables in the main() function.
3. Ask the user to put the number of data points and storing
it in n and the values of data points of x and y axis in the
arrays x[] and y[] reaspectively.
4. Repeat the steps for i ≤ n , where i is initialised by 0 and is
increasing by +1 with every itteration.
5. Set ,
sumx=sumx +x[i].
sumx2=sumx2 +x[i]*x[i].
sumy=sumy +y[i].
sumxy=sumxy +x[i]*y[i].
[End of loop]
6. Set ,
a=((sumx2*sumy -sumx*sumxy)*1.0/(n*sumx2-
sumx*sumx)*1.0).
b=((n*sumxy-sumx*sumy)*1.0/(n*sumx2-
sumx*sumx)*1.0).
7. print the values of a and b in y=mx+c format.
8. END.
SOURCE CODE :
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main()
{
int n,i,x[20],y[20],sumx=0,sumy=0,sumxy=0,sumx2=0;
float a,b;
printf("\nC program for Linear Curve Fitting \n ");
printf("\nEnter the value of number of terms n:");
scanf("%d",&n);
printf("\nEnter the values of x:\n");
for(i=0;i<=n-1;i++)
{ PAGE
NO.:21
printf("\nx%d : ",i);
scanf("\t%d",&x[i]);
}
printf("\nEnter the values of y:\n");
for(i=0;i<=n-1;i++)
{
printf("\ny%d : ",i);
scanf("\t%d",&y[i]);
}
for(i=0;i<=n-1;i++)
{
sumx=sumx +x[i];
sumx2=sumx2 +x[i]*x[i];
sumy=sumy +y[i];
sumxy=sumxy +x[i]*y[i];
}
a=((sumx2*sumy -sumx*sumxy)*1.0/(n*sumx2-
sumx*sumx)*1.0);
b=((n*sumxy-sumx*sumy)*1.0/(n*sumx2-
sumx*sumx)*1.0);
printf("\n\nThe line is Y=%3.3f +%3.3f X",a,b);
return(0);
}
OUTPUT :
C program for Linear Curve Fitting
Enter the value of number of terms n:4
Enter the values of x:
x0 : 1
x1 : 2
x2 : 3
x3 : 6

Enter the values of y:


y0 : 2
y1 : 4
y2 : 5
y3 : 5

The line is Y=2.500 +0.500 X


Process returned 0 (0x0) execution time : 21.476 s

______________________________
SIGNATURE OF THE TEACHER
DATE : 04.12.2023

You might also like