Home > Backend Development > C++ > C program to calculate linear regression

C program to calculate linear regression

王林
Release: 2023-08-25 23:45:05
forward
1046 people have browsed it

C program to calculate linear regression

Question

Write a program to implement the linear regression algorithm.

Users need to enter the total number of values.

Solution

The solution to calculate linear regression using the C programming language is as follows:

Linear regression finds the relationship between two variables by connecting a linear equation to the observed data Relationship. One variable is the explanatory variable and the other is the dependent variable.

The logic of linear regression is as follows:

for(i=0;i<n;i++){
   printf("enter values of x and y");
   scanf("%f%f",&x,&y);
   sumx=sumx+x;
   sumxsq=sumxsq+(x*x);
   sumy=sumy+y;
   sumxy=sumxy+(x*y);
}

d=n*sumxsq-sumx*sumx;
m=(n*sumxy-sumx*sumy)/d;
c=(sumy*sumxsq-sumx*sumxy)/d;
Copy after login

Finally, print m and c.

Example

Following is the C program to compute the linear regression

Live Demo

#include<math.h>
#include<stdio.h>
main(){
   int n,i;
   float x,y,m,c,d;
   float sumx=0,sumxsq=0,sumy=0,sumxy=0;
   printf("enter the number of values for n:");
   scanf("%d",&n);
   for(i=0;i<n;i++){
      printf("enter values of x and y");
      scanf("%f%f",&x,&y);
      sumx=sumx+x;
      sumxsq=sumxsq+(x*x);
      sumy=sumy+y;
      sumxy=sumxy+(x*y);
   }
   d=n*sumxsq-sumx*sumx;
   m=(n*sumxy-sumx*sumy)/d;
   c=(sumy*sumxsq-sumx*sumxy)/d;
   printf("M=%f\tC=%f</p><p>",m,c);
}
Copy after login

Output

When the above program is executed, it produces the following result −

enter the number of values for n:5
enter values of x and y1 5
enter values of x and y2 6
enter values of x and y2 4
enter values of x and y3 7
enter values of x and y1 1
M=2.000000 C=1.000000
Copy after login

The above is the detailed content of C program to calculate linear regression. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template