Slope & Intercept

Computer Methods in Chemical Engineering


Problem Statement: Write a program to find the slope and y-intercept for a given set of data. This excercise tries to review & practice the fundamentals of programming (e.g., input, output, iteration loop, and condition if-then-else),

Test case: the 2-column x-y data contained in random2.dat.

The general steps are:

  1. General comments (purpose, algorithm, list of variables/definitions, authorship, etc.)
  2. Declare variables used.
  3. Print a brief header to inform the user what the program does.
  4. Input x-y data (It is better to write a flexible program to handle many types of data.)
    • Either:
      • open a file (for large number of points)
      • read in data until end-of-file is reached.
    • Or
      • read from the keyboard via manual entry (for small number of points) until you tell the computer there are no more data.
    • Keep track of the number of data points read.
    In Mathcad, we read the 2-column x-y data contained in random2.dat with the READPRN routine and extract out the x and y data.
  5. Find the various sums needed for calculating slope and intercept:
            sum(xi)
            sum(yi)
            sum(xi*xi)
            sum(xi*yi)
        
    In Mathcad, this step is a matter of being able to type in the correct formula with the correct summation operator/function.
  6. Find the average of x and y based on the following formula.
                   sum(xi)
            xave = --------
                    ipt
    
                   sum(yi)
            yave = --------
                    ipt
        
    Mathcad provides a function "mean", but we can practice this too.
  7. Find the slope and y-intercept according to the following formula:
                     sum(xi*yi) - sum(xi)*yave
            slope = --------------------------
                     sum(xi*xi) - sum(xi)*xave
    
            y-intercept = yave - slope*xave
        
    Mathcad provides functions "slope" and "intercept", but we can practice writing our functions and compare to the ones Mathcad provides.
  8. Output slope and intercept calculated above with print or write statement. Mathcad's equivalent is "=", i.e., a regular equal sign that means print/write/display.
  9. Done (end).

Solution:

Program Listing
c-----------------------------------------------------------------------
c Find the least squares linear fit
c   y = a + b*x
c
c Read (x,y) data from a file in a two-column format or from the keyboard
c
c Variables ...
c   x(i)   ... independent variable
c   y(i)   ... dependent variable
c   ipt    ... number of independent measurements
c   a      ... y-intercept
c   b      ... slope
c   sumx   ... sum of x(i)
c   sumy   ... sum of y(i)
c   sumxx  ... sum of x(i)*x(i)
c   sumxy  ... sum of x(i)*y(i)
c   nmax   ... maximum number of data points
c-----------------------------------------------------------------------
c Program Note:
c   Calculate slope and intercept from the sum of x, y, xy, etc.
c-----------------------------------------------------------------------
c Instructor: Nam Sun Wang
c-----------------------------------------------------------------------

c Change the following parameter to handle more data points ------------
      parameter (nmax=1000)
      dimension x(nmax), y(nmax)
      character fname*40, resp*1, mresp*1

c Print program header -------------------------------------------------
      write(*,*)'************************************'
      write(*,*)'Find the least squares linear fit***'
      write(*,*)'  y = a + b*x                       '
      write(*,*)'************************************'
      write(*,*)

      write(*,600)' Read data from a file (Y/n)? '
        read(*,500)resp

c Read (x,y) manually from a terminal ----------------------------------
      if(resp .eq. 'n' .or. resp .eq. 'N')then
        write(*,*)'Enter x,y:'
        do 10 i=1, nmax
          write(*,608)' x(', i, ')= '
            read(*,*)x(i)
          write(*,608)' y(', i, ')= '
            read(*,*)y(i)
          write(*,600)' More data (Y/n)? '
            read(*,500)mresp
            if(mresp .eq. 'n' .or. mresp .eq. 'N')goto 11
10      continue
11      ipt=i
c Read data x, y from a file (may include a header) --------------------
      else
        write(*,600)' Filename containing x-y data in 2-column format: '
        read(*,500)fname
        open(1, file=fname, status='old')
        do 20 i=1, nmax
19        read(1,*,err=19,end=21)x(i), y(i)
20      continue
21      close(1)
        ipt=i-1
      endif

c Report the number of points read -------------------------------------
      write(*,*)' Number of points read = ',ipt

c Find the various sums needed for calculating slope and intercept -----
      do 30 i=1, ipt
        sumx  = sumx  + x(i)
        sumy  = sumy  + y(i)
        sumxx = sumxx + x(i)*x(i)
        sumxy = sumxy + x(i)*y(i)
30    continue

c Find the average of x and y ------------------------------------------
      xave = sumx / float(ipt)
      yave = sumy / float(ipt)

c Find the slope (b) and y-intercept (a)
      b = (sumxy - sumx*yave) / (sumxx - sumx*xave)
      a = yave - b*xave

c Print the intercept and slope ----------------------------------------
      write(*,*)' intercept = ', a
      write(*,*)' slope =     ', b

c Some formats ---------------------------------------------------------
500   format(a)
600   format(a\)
608   format(a,i2,a\)
      end


Problem Statement: Rewrite the above slope-intercept program in a structured subroutine format. Your program should have a subroutine that acts on any independent data x and dependent data y and returns the slope and intercept. Test case: the 2-column x-y data contained in random2.dat.

Solution:


Problem Statement: Read the 2-column x-y data contained in random2.dat with the READPRN routine in Mathcad and extract out the x and y data. Find the slope and intercept according to the formula given below.

             sum(xi*yi) - sum(xi)*yave
    slope = --------------------------
             sum(xi*xi) - sum(xi)*xave

    y-intercept = yave - slope*xave
Plot the original data as discrete points (e.g., "x", "o", or ".") and the regression line as a solid line. Compare your results to those obtained from the slope and intercept routines in Mathcad.

Solution:


QBasic versions of the intercept-slope calculation. With slight modification (e.g., input from Excel worksheet and output to Excel worksheet instead of print to computer screen), the code can be used in VBA. On the other hand, Excel also already has built-in functions to find slope and intercept. The objective here is to show that there is almost a line-by-line correspondence between different computer languages or math packages. The sequence of steps is identical; only the syntax varies.

Solution:


Return to Prof. Nam Sun Wang's Home Page
Return to Computer Methods inChemical Engineering (CHBE250)

Computer Methods in Chemical Engineering -- Slope & Intercept
Forward comments to:
Nam Sun Wang
Department of Chemical & Biomolecular Engineering
University of Maryland
College Park, MD 20742-2111
301-405-1910 (voice)
301-314-9126 (FAX)
e-mail: nsw@umd.edu ©1996-2012 by Nam Sun Wang
UMCP logo