C Program for Linear Regression Method
This C program implements Linear Regression Method using Least Square Method to find linear equation of best fit.
In this program we first read n data points from user and then we implement linear regression using C programming language as follow:
C Program: Linear Regression (Fitting y = a+bx)
#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();
/* Input */
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]);
}
/* Calculating Required Sum */
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];
}
/* Calculating a and b */
b = (n*sumXY-sumX*sumY)/(n*sumX2-sumX*sumX);
a = (sumY - b*sumX)/n;
/* Displaying value of a and b */
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);
}
C Program Output: Linear Regression
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 Note: ↲ indicates ENTER is pressed.
Recommended Readings