NB. *************************************************************************** NB. NB. L I N R E G NB. NB. Program: LINREG NB. NB. Programmer: Dr. David G. Simpson NB. Department of Physical Science NB. Prince George's Community College NB. Largo, Maryland 20774 NB. NB. Date: February 2, 2002 NB. NB. Language: J NB. NB. Description: This program performs a linear regression analysis for a NB. set of data given as (X,Y) pairs. The output from the NB. program is the slope and y-intercept of the least-squares NB. best fit straight line through the data points. NB. NB. Note: To run, load this script and type "linreg 0". NB. NB. *************************************************************************** linreg =: 3 : 0 NB. NB. Print introductory message NB. 'LINREG - Perform linear regression' 1!:2[2 ' (Enter _9999 for X to stop data entry and perform linear regression)' 1!:2[2 NB. NB. Initialize the sums NB. n =. 0 sumx =. 0 sumx2 =. 0 sumxy =. 0 sumy =. 0 sumy2 =. 0 NB. NB. Start of data entry loop NB. while. 1 do. NB. begin data entry loop ' ' 1!:2[2 NB. print blank line at console 'Enter X Y: ' 1!:2[2 NB. prompt for X and Y d =. ". 1!:1[1 NB. read in X and Y as an array d if. 0{d = _9999 NB. if X = -9999.. do. break. end. NB. ..then break out of loop x =. 0{d NB. else set x to first element y =. 1{d NB. set y as second element n =. n + 1 NB. increment number of points sumx =. sumx + x NB. sum of x sumx2 =. sumx2 + *: x NB. sum of x squared sumxy =. sumxy + x * y NB. sum of xy sumy =. sumy + y NB. sum of y sumy2 =. sumy2 + *: y NB. sum of y squared end. NB. NB. Compute slope (m), y-intercept (b), and correlation coefficient (r) NB. m =. ((n * sumxy) - (sumx * sumy)) % ((n * sumx2) - *:sumx) b =. ((sumy * sumx2) - (sumx * sumxy)) % ((n * sumx2) - *:sumx) r =. (sumxy - sumx * sumy % n) % %:((sumx2 - (*:sumx) % n) * (sumy2 - (*:sumy) % n)) NB. NB. Print results. NB. ' ' 1!:2[2 NB. print blank line at console ('Slope m = ', 0j6":m) 1!:2[2 ('y-intercept b = ', 0j6":b) 1!:2[2 ('Correlation r = ', 0j6":r) )