Solve Regression Equations through C language code


SUBMITTED BY: Neutrino

DATE: Dec. 10, 2020, 10:58 a.m.

FORMAT: Text only

SIZE: 2.1 kB

HITS: 450

  1. #include<stdio.h>
  2. #include<math.h>
  3. #define N 30
  4. double bxy(double mean_x,double mean_y,double x[],double y[],int n)
  5. {
  6. double a=0,c=0,b_xy=0;
  7. for(int i=0; i<n; i++)
  8. {
  9. a+=(x[i]-mean_x)*(y[i]-mean_y);
  10. c+=pow((y[i]-mean_y),2);
  11. }
  12. b_xy=a/c;
  13. return b_xy;
  14. }
  15. double byx(double mean_x,double mean_y,double x[],double y[],int n)
  16. {
  17. double a=0,c=0,b_yx=0;
  18. for(int i=0; i<n; i++)
  19. {
  20. a+=(x[i]-mean_x)*(y[i]-mean_y);
  21. c+=pow((x[i]-mean_x),2);
  22. }
  23. b_yx=a/c;
  24. return b_yx;
  25. }
  26. int main()
  27. {
  28. double x[N],y[N],sum_x=0,sum_y=0,mean_x,mean_y,r;
  29. int n;
  30. printf("Enter the no of observations : ");
  31. scanf("%d",&n);
  32. printf("Enter the observations for x-series\n");
  33. for(int i=0; i<n; i++)
  34. {
  35. printf("\nObservation no [%d] = ",i+1);
  36. scanf("%lf",&x[i]);
  37. sum_x+=x[i];
  38. }
  39. printf("\nEnter the observations for y-series\n");
  40. for(int i=0; i<n; i++)
  41. {
  42. printf("\nObservation no [%d] = ",i+1);
  43. scanf("%lf",&y[i]);
  44. sum_y+=y[i];
  45. }
  46. mean_x=sum_x/n;
  47. mean_y=sum_y/n;
  48. // printf("mean of x and y is %lf and %lf",mean_x,mean_y);
  49. r=sqrt(bxy(mean_x,mean_y,x,y,n)* byx(mean_x,mean_y,x,y,n));
  50. printf("x\ty\t(x-xbar)\t(y-ybar)\t(x-xbar)sqr\t(y-ybar)sqr\t(x-xbar)(y-ybar)\n");
  51. for (int i=0;i<n;i++)
  52. {
  53. printf("%.0f\t%.0f\t%f\t%f\t%f\t%f\t%f\n",x[i],y[i],x[i]-mean_x,y[i]-mean_y,(x[i]-mean_x)*(x[i]-mean_x),(y[i]-mean_y)*(y[i]-mean_y),(x[i]-mean_x)*(y[i]-mean_y));
  54. }
  55. printf("\nThe regression coefficients of series are %.4lf and %.4lf \n",bxy(mean_x,mean_y,x,y,n), byx(mean_x,mean_y,x,y,n));
  56. printf("The equation of regression of y on x is y = %.3f x + %lf\n",byx(mean_x,mean_y,x,y,n),- byx(mean_x,mean_y,x,y,n)*mean_x+mean_y);
  57. printf("The equation of regression of x on y is x = %.3f y + %lf\n",bxy(mean_x,mean_y,x,y,n),- bxy(mean_x,mean_y,x,y,n)*mean_y+mean_x);
  58. printf("The correlation coefficient r is %lf ",r);
  59. return 0;
  60. }

comments powered by Disqus