double Statistic::LineFit(const double *const x, const double *const y, const size_t n, double *m, double *b) { int error = 0; double sumx = 0, sumy = 0, sumx2 = 0, sumxy = 0; double dn = (double) n; size_t i; if (n <= 1) { *m = 0; *b = 0; error = 1; } else { double divisor; error = 0; for (i = 0; i < n; i++) { sumx += x[i]; sumy += y[i]; sumx2 += (x[i] * x[i]); sumxy += (x[i] * y[i]); } divisor = (sumx2 - ((sumx * sumx) / dn)); if (divisor != 0) { *m = (sumxy - ((sumx * sumy) / dn)) / divisor; *b = (sumy - ((*m) * sumx)) / dn; } else { *m = 0; *b = 0; error = 2; } } return *m; };
int main() { // exact line: double x0[] = {-1, 0, 1, 2, 3}; double y0[] = {-1, 0, 1, 2, 3}; // noisy line: double x1[] = {-1.1, 0.01, .9999, 1.99998, 3.01}; double y1[] = {-1.02, -.00001, 1.002, 1.99872, 2.999973}; size_t length = sizeof x0 / sizeof x0[0]; double m; double b; linfit(x0, y0, length, &m, &b); printf("Slope is %f, intercept is %f\n", m, b); linfit(x1, y1, length, &m, &b); printf("Slope is %f, intercept is %f\n", m, b); cin.get(); return 0; }