## File: Fitting-linear-regression-example.html

package info (click to toggle)
gsl-ref-html 2.3-1
• area: non-free
• in suites: bullseye, buster, sid
• size: 6,876 kB
• ctags: 4,574
• sloc: makefile: 35
 file content (155 lines) | stat: -rw-r--r-- 6,234 bytes parent folder | download
 `123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155` `````` GNU Scientific Library – Reference Manual: Fitting linear regression example

38.8.1 Simple Linear Regression Example

The following program computes a least squares straight-line fit to a simple dataset, and outputs the best-fit line and its associated one standard-deviation error bars.

#include <stdio.h> #include <gsl/gsl_fit.h>  int main (void) {   int i, n = 4;   double x[4] = { 1970, 1980, 1990, 2000 };   double y[4] = {   12,   11,   14,   13 };   double w[4] = {  0.1,  0.2,  0.3,  0.4 };    double c0, c1, cov00, cov01, cov11, chisq;    gsl_fit_wlinear (x, 1, w, 1, y, 1, n,                     &c0, &c1, &cov00, &cov01, &cov11,                     &chisq);    printf ("# best fit: Y = %g + %g X\n", c0, c1);   printf ("# covariance matrix:\n");   printf ("# [ %g, %g\n#   %g, %g]\n",            cov00, cov01, cov01, cov11);   printf ("# chisq = %g\n", chisq);    for (i = 0; i < n; i++)     printf ("data: %g %g %g\n",                     x[i], y[i], 1/sqrt(w[i]));    printf ("\n");    for (i = -30; i < 130; i++)     {       double xf = x[0] + (i/100.0) * (x[n-1] - x[0]);       double yf, yf_err;        gsl_fit_linear_est (xf,                            c0, c1,                            cov00, cov01, cov11,                            &yf, &yf_err);        printf ("fit: %g %g\n", xf, yf);       printf ("hi : %g %g\n", xf, yf + yf_err);       printf ("lo : %g %g\n", xf, yf - yf_err);     }   return 0; }

The following commands extract the data from the output of the program and display it using the GNU plotutils graph utility,

\$ ./demo > tmp \$ more tmp # best fit: Y = -106.6 + 0.06 X # covariance matrix: # [ 39602, -19.9 #   -19.9, 0.01] # chisq = 0.8  \$ for n in data fit hi lo ;     do       grep "^\$n" tmp | cut -d: -f2 > \$n ;     done \$ graph -T X -X x -Y y -y 0 20 -m 0 -S 2 -Ie data       -S 0 -I a -m 1 fit -m 2 hi -m 2 lo

``````