/*--------------------------------------------------------------------------*/ /* Linear least squares fit */ /* In Linux compile with */ /* gcc -o lsm lsm.c -lm */ /* Usage: */ /* lsm < datafile */ /* where datafile is a file containing two columns */ /* e.g. time and altitude as real numbers */ /* The program will fit a parabola y=a+bx+cx^2 to the data */ /*--------------------------------------------------------------------------*/ #include #include #include #include #include #include #define N 100 main() { double a[N][3], b[N], s[3][3], c[3], x0, x1, x2, d, d0, d1, d2, tim, alt, tmp, x, y ; int n, i, j, k ; n = -1 ; while ((scanf(" %lf %lf", &tim, &alt)) != EOF) { n++ ; a[n][0] = 1.0 ; a[n][1] = tim ; a[n][2] = tim * tim ; b[n] = alt ; } /* a transpose a */ for (i=0; i<3; i++) for (j=0; j<3; j++) { tmp = 0.0; for (k=0; k<=n; k++) tmp += a[k][i] * a[k][j] ; s[i][j] = tmp ; } /* a transpose b */ for (i=0; i<3; i++) { tmp = 0; for (k=0; k<=n; k++) tmp += a[k][i] * b[k] ; c[i] = tmp ; } /* determinant */ d = s[0][0] * (s[1][1] * s[2][2] - s[1][2] * s[2][1]) - s[1][0] * (s[0][1] * s[2][2] - s[0][2] * s[2][1]) + s[2][0] * (s[0][1] * s[1][2] - s[0][2] * s[1][1]) ; /* cofactors */ d0 = c[0] * (s[1][1] * s[2][2] - s[1][2] * s[2][1]) - c[1] * (s[0][1] * s[2][2] - s[0][2] * s[2][1]) + c[2] * (s[0][1] * s[1][2] - s[0][2] * s[1][1]) ; d1 = s[0][0] * (c[1] * s[2][2] - s[1][2] * c[2]) - s[1][0] * (c[0] * s[2][2] - s[0][2] * c[2]) + s[2][0] * (c[0] * s[1][2] - s[0][2] * c[1]) ; d2 = s[0][0] * (s[1][1] * c[2] - c[1] * s[2][1]) - s[1][0] * (s[0][1] * c[2] - c[0] * s[2][1]) + s[2][0] * (s[0][1] * c[1] - c[0] * s[1][1]) ; x0 = d0 / d ; x1 = d1 / d ; x2 = d2 / d ; printf("y = %f + %f * x + %f * x**2\n", x0, x1, x2) ; x = -0.5 * x1 / x2 ; y = x0 + x1 * x + x2 * x * x ; printf("coordinates of the apex: x=%f y=%f\n", x, y) ; }