#*************************************************************************** # # L I N R E G # # Program: LINREG # # Programmer: Dr. David G. Simpson # Department of Physical Sciences and Engineering # Prince George's Community College # Largo, Maryland 20774 # # Date: February 2, 2007 # # Language: Icon # # Description: This program performs a linear regression analysis for a # set of data given as (x,y) pairs. The output from the # program is the slope and y-intercept of the least-squares # best fit straight line through the data points. # #*************************************************************************** #*************************************************************************** # main() #*************************************************************************** procedure main() #--------------------------------------------------------------------------- # Initialize data. #--------------------------------------------------------------------------- n := 0.0 # number of data points sumx := 0.0 # sum of x sumx2 := 0.0 # sum of x**2 sumxy := 0.0 # sum of x * y sumy := 0.0 # sum of y sumy2 := 0.0 # sum of y**2 #--------------------------------------------------------------------------- # Print introductory message. #--------------------------------------------------------------------------- write("LINREG - Perform linear regression") write(" (Enter END to stop data entry and compute linear regression.)") #--------------------------------------------------------------------------- # Enter data and accumulate sums. #--------------------------------------------------------------------------- repeat { # loop for all data points write ("Enter x: ") # prompt for x x := read() # read x into string str if (match(x,"end") | # if no more points.. match(x,"END")) then break # ..then go compute least sqrs write ("Enter y: ") # prompt for y y := read() # read y into string str n +:= 1.0 # increment num of data points sumx +:= x # compute sum of x sumx2 +:= x * x # compute sum of x**2 sumxy +:= x * y # compute sum of x * y sumy +:= y # compute sum of y sumy2 +:= y * y # compute sum of y**2 } # loop again for more data #--------------------------------------------------------------------------- # Compute least-squares best fit straight line. #--------------------------------------------------------------------------- m := (n * sumxy - sumx * sumy) / # compute slope (n * sumx2 - sumx*sumx) b := (sumy * sumx2 - sumx * sumxy) / # compute y-intercept (n * sumx2 - sumx*sumx) r := (sumxy - sumx * sumy / n) / # compute correlation coeff sqrt((sumx2 - sumx*sumx/n) * (sumy2 - sumy*sumy/n)) #--------------------------------------------------------------------------- # Print results and return to operating system. #--------------------------------------------------------------------------- write ("\nSlope m = ",m) write ("y-intercept b = ",b) write ("Correlation r = ",r) end