Program 5: Curve-fitting: Least squares fitting
Aim;
Write a C program to implements Linear Regression Method using using Least
Square Method to find linear equation of best fit.
Algorithm: Fitting y = a + bx
1. Start
2. Read Number of Data (n)
3. For i=1 to n:
Read Xi and Yi
Next i
4. Initialize:
sumX = 0
sumX2 = 0
sumY = 0
sumXY = 0
5. Calculate Required Sum
For i=1 to n:
sumX = sumX + Xi
sumX2 = sumX2 + Xi * Xi
sumY = sumY + Yi
sumXY = sumXY + Xi * Yi
Next i
6. Calculate Required Constant a and b of y = a + bx:
b = (n * sumXY - sumX * sumY)/(n*sumX2 - sumX * sumX)
a = (sumY - b*sumX)/n
7. Display value of a and b
8. Stop
Flowchart:
Program:
#include<stdio.h>
#include<conio.h>
#define S 50
int main()
{
int n, i;
float x[S], y[S], sumX=0, sumX2=0, sumY=0, sumXY=0, a, b;
clrscr();
printf("How many data points?\n");
scanf("%d", &n);
printf("Enter data:\n");
for(i=1;i<=n;i++)
{
printf("x[%d]=",i);
scanf("%f", &x[i]);
printf("y[%d]=",i);
scanf("%f", &y[i]);
}
for(i=1;i<=n;i++)
{
sumX = sumX + x[i];
sumX2 = sumX2 + x[i]*x[i];
sumY = sumY + y[i];
sumXY = sumXY + x[i]*y[i];
}
b = (n*sumXY-sumX*sumY)/(n*sumX2-sumX*sumX);
a = (sumY - b*sumX)/n;
printf("Values are: a=%0.2f and b = %0.2f",a,b);
printf("\nEquation of best fit is: y = %0.2f + %0.2fx",a,b);
getch();
return(0);
}
Output:
How many data points?
4
Enter data:
x[1] = 0
y[1] = -1
x[2] = 2
y[2] = 5
x[3] = 5
y[3] = 12
x[4] = 7
y[4] = 20
Values are: a=-1.14 and b=2.90
Equation of best fit is: y = -1.14 + 2.90x
Result:
Thus a C Program using to implements curve fitting using Least Square Method to find linear equation
of best fit has been successfully verified and executed, and the output was obtained.