
编写一个程序来实现线性回归算法。
用户需要输入总共的数值个数。
使用C编程语言计算线性回归的解决方案如下:
线性回归通过将线性方程与观测数据相连接来找到两个变量之间的关系。一个变量是解释变量,另一个是因变量。
关于线性回归的逻辑如下所述:
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;Finally, print m and c.
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);
}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
以上就是C程序计算线性回归的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号