Page t045, go to NEXT, PREVIOUS, INDEX

Example: Line Fit


Line fit or linear regression, part 1

      #include <stdio.h>

      void linefit ()
      {
        /* Declarations. */
        int n;          /* number of points */
        float *x, *y;   /* x- and y-values of points */
        double sx, sy;  /* sums for x and y, respectively */

        /* Create arrays with desired size. */
        printf ("Number of points: ");
        scanf ("%d", &n);
        x = (float *) malloc (n*sizeof(float));
        y = (float *) malloc (n*sizeof(float));

        /* Read the data points. */
        { int i;
          for ( i = 0; i < n; i++ )
          { printf ("X-value for point %d: ", i+1);
            scanf ("%f", &x[i]);
            printf ("Y-value for point %d: ", i+1);
            scanf ("%f", &y[i]);
          }
        }

        /* Accumulate sums sx and sy in double precision. */
        sx = 0.0;
        sy = 0.0;
        { int i;
          for ( i = 0; i < n; i++ )
          { sx += x[i];
            sy += y[i];
          }
        }

C Course, 22-jan-1997, Peter Klok, pfk@hef.kun.nl