#!/usr/bin/python #*********************************************************************************************************************************** # # 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: March 7, 2012 # # Language: Python 3 # # Version: 1.01a (February 24, 2023) # # 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. # # # Files: Source files: # # linreg.py Main program # # Notes: # #*********************************************************************************************************************************** from math import sqrt # # Print introductory message. # print (' LINREG - perform linear regression') print (' (enter ''end'' to stop data entry and compute linear regression.)') # # Initialize sums. # n = 0.0 sumx = 0.0 sumx2 = 0.0 sumxy = 0.0 sumy = 0.0 sumy2 = 0.0 data_entry = True # # Start of data entry loop. # while (data_entry): str = input('\n Enter x: ') if ((str == 'end') or (str == 'END')): data_entry = False else: x = float(str) y = float(input(' Enter y: ')) n += 1.0 # compute sums sumx += x sumx2 += x * x sumxy += x * y sumy += y sumy2 += y * y # # Compute slope (m), y-intercept (b), and correlation coefficient (r). # m = (n * sumxy - sumx * sumy) / (n * sumx2 - sumx**2) b = (sumy * sumx2 - sumx * sumxy) / (n * sumx2 - sumx**2) r = (sumxy - sumx * sumy / n) / sqrt((sumx2 - sumx**2/n) * (sumy2 - sumy**2/n)) # # Print results. # print ('\n slope m = ', m) print (' y-intercept b = ', b) print (' correlation r = ', r)