Thursday 28 July 2016

C program for regression / line of best fit for when there is scatter of data. the equation is y = a + bx

#include<stdio.h>

main()
{
int i, noofvar;
float xi, yi, xsum, ysum, xysum, xxsum, a, b;
xsum = 0;
ysum = 0;
xysum = 0;
xxsum = 0;
printf("The output of this program will give two values a and b.\n");
printf("a and b can be used in the equation y =  a + bx.\n");
printf("Using the equation with a and b will give a regression.\n");
printf("A plot from the equation will give a line of best fit.\n");
printf("Enter the number of pairs of x and y variables:\n");
scanf("%i", &noofvar);
for(i = 1; i<=noofvar; i++)
{
printf("Enter x value %i\n",i);
scanf("%f", &xi);
printf("Enter y value %i\n", i);
scanf("%f", &yi);
xsum = xsum + xi;
ysum = ysum + yi;
xysum = xysum + xi * yi;
xxsum = xxsum + xi * xi;
}

b = (noofvar * xysum - xsum * ysum) / (noofvar * xxsum - xsum * xsum);
a = (ysum - b * xsum) / noofvar;
printf("Value of a is %f\n", a);
printf("Value of b is %f\n", b);
}

No comments:

Post a Comment