'*************************bestfitline() subroutine******************* ' ' purpose: takes the points in the history array and computes ' the best fit line (the line that lies closest to all the points ' ' input: history array ' ' output: draws the best fit line in the picturebox control ' displays beginning and end coordinates of the best fit line ' displays the slope and y-intercept of the best fit line ' '******************************************************************** Sub bestfitline() Dim shiftx As Integer 'how much to shift x and y to make screen Dim shifty As Integer 'work better with cartesian coordinates shiftx = 80 'make origin start at middle of screen shifty = 120 'and also shift it to the bottom of the screen Dim vertline As Integer 'where to draw the line if the slope is undefined vertline = history(0, 1) Dim sumx As Double 'sumx is summation of x Dim sumy As Double 'sumy is summation of y Dim sumxy As Double 'sumxy is summation of x*y Dim sumxsq As Double 'sumxsq is summation of x*x Dim i As Integer 'i is a counter Dim a As Double 'a and b derive from line formula-->y=a+bx Dim b As Double Dim temp1 As Double Dim temp2 As Double 'best fit line goes from (x1,y1) to (x2,y2) Dim x1 As Double Dim y1 As Double Dim x2 As Double Dim y2 As Double sumx = 0 sumy = 0 sumxy = 0 sumxsq = 0 For i = 0 To bfln - 1 sumx = sumx + (history(i, 1) - shiftx) sumy = sumy + (shifty - history(i, 0)) sumxy = sumxy + ((history(i, 1) - shiftx) * (shifty - history(i, 0))) sumxsq = sumxsq + ((history(i, 1) - shiftx) * (history(i, 1) - shiftx)) Next i temp1 = (sumxsq * sumy) - (sumx * sumxy) temp2 = (bfln * sumxsq) - (sumx ^ 2) If Not (temp2 = 0) Then a = temp1 / temp2 End If temp1 = (bfln * sumxy) - (sumx * sumy) If Not (temp2 = 0) Then b = temp1 / temp2 End If 'y=a+bx 'x=(y-a)/b y1 = history(0, 0) y2 = history(bfln - 1, 0) If b = 0 Then 'vertical line problem-->vertical slope means division by zero x1 = vertline x2 = vertline Else 'translate back into screen coordinates from shifted cartesian coordinates x1 = (((shifty - y1) - a) / b) + shiftx x2 = (((shifty - y2) - a) / b) + shiftx End If lx1.Caption = x1 lx2.Caption = x2 ly1.Caption = y1 ly2.Caption = y2 lb.Caption = a If b = 0 Then lm.Caption = "infinity" Else lm.Caption = b End If Picture4.ScaleMode = vbPixels Picture4.DrawWidth = 5 Picture4.Line (x1, y1)-(x2, y2), RGB(255, 0, 0) End Sub