Please do in C programming language. Write a program to perform linear regressio
ID: 3807098 • Letter: P
Question
Please do in C programming language.
Write a program to perform linear regression between two data sets. The code should return the slope and y-intercept for the best-fit line through the data. Both data sets should be read from the files provided. Background Linear regression is the process of fitting a set of data pairs to a straight line. The assumption is that the data can be modeled by linear relationship. Our task will be to extract from the seemingly noise-computed data the parameters of the linear model. We are given a set of data pairs, {x_t, v_t}, 0 lessthanorequalto iExplanation / Answer
C program
#include<stdio.h>
// function definitions
float mean(float x[],int N);
float slop(float x[],float y[],float Mx,float My,int N);
float intercept(float Mx,float My,float Alf);
int main() // main function
{
float x[1000],y[1000],Mx,My,Alf,Bet,sum1 = 0,sum2 = 0; // variable declerations
int N,i=0,j;
FILE *Pt;
Pt = fopen("f1.txt","r");
while(fscanf(Pt,"%f%f",&x[i],&y[i])!=EOF) i++; // reading the data from the file f1 change it to f2 and f3 for f2 and f3 regression
N = i; // number of points in the data
Mx = mean(x,N); // computing mean of x
My = mean(y,N); // computing mean of y
Alf = slop(x,y,Mx,My,N); // computing alfa
Bet = intercept(Mx,My,Alf);// computing beta
printf("Alfa = %f Beta = %f ",Alf,Bet); // printing the result
return 0;
}// function to fiund the mean
float mean(float x[],int N)
{
int i; float sum = 0;
for(i = 0;i<N;i++)// sum of all x
sum = sum + x[i]; // computing summation of x
return sum/N;
}//function to find the slop
float slop(float x[],float y[],float Mx,float My,int N)
{
float sum1 = 0,sum2 = 0;
int i;
for(i = 0;i<N;i++)
{
sum1 = sum1 + (x[i]-Mx)*(y[i]-My);
sum2 = sum2 + (x[i]-Mx)*(x[i]-Mx);
}
return sum1/sum2;
}// function to find the intercept
float intercept(float Mx,float My,float Alf)
{
return My-Alf*Mx;
}
Sample Text file f1.txt
0 0
1 6.8800
1.5000 15.4800
2 27.5200
2.5000 43
3 61.9200
3.2700 73.5600
3.4960 84.0800
3.5000 84.2800
3.5240 85.4400
3.7320 95.8200
4 110.1000
4.5000 139.3000
5 172
OUTPUT
$ ./a.out
Alfa = 34.534920 Beta = -29.807976