formula:
C code:
#include <stdio.h>
#define ARRAYLEN(x) ((sizeof(x))/(sizeof(x[0])))
void
Least_squares(const double *x, const double *y, const int n, double *b, double *a)
{
int i;
double sum_x = 0.0; /*sum of x*/
double sum_y = 0.0; /*sum of y*/
double sum_xy = 0.0; /*sum of x*y*/
double sum_x2 = 0.0; /*sum of x^2*/
double x_average; /*average of x*/
double y_average; /*average of y*/
for (i = 0; i < n; i++) {
sum_x += x[i];
sum_y += y[i];
sum_x2 += x[i] * x[i];
sum_xy += x[i]*y[i];
}
x_average =sum_x / n;
y_average =sum_y / n;
*b = (sum_xy - n * x_average * y_average) / (sum_x2 - n * x_average * x_average);
*a = y_average - (*b) * x_average;
return;
}
double x[] ={1.0, 2.1, 2.9, 4.2, 5.3};
double y[] ={5.1, 9.3, 13.0, 17.9, 22.0};
int
main(int argc, char *argv[])
{
double b , a ;
Least_squares(x, y, ARRAYLEN(x), &b, &a);
printf("a = %lf b = %lf \n", b, a);
return 0 ;
}