353 - Topic 00.5 - Best Fit Line - Chapter 2

11 days ago by Professor353

pts = [(-1,4),(-1,6),(0,4),(2,2),(2,-1),(5,0)] var('x') n=len(pts) xs = [] xsq = [] ys = [] xy = [] ysq = [] for k in range(n): xtemp = pts[k][0] ytemp = pts[k][1] xs.append(xtemp) ys.append(ytemp) xsq.append(xtemp^2) ysq.append(ytemp^2) xy.append(xtemp*ytemp) SUMx = sum(xs) SUMy = sum(ys) SUMxy = sum(xy) SUMxsq = sum(xsq) SUMysq = sum(ysq) A = matrix([[SUMxsq,SUMx],[SUMx,n]]) show(A) b = matrix([[SUMxy],[SUMy]]) show(b) c = A.inverse()*b m = float(c[0][0]) intercept = float(c[1][0]) T = "$ y = %s"%str(latex(m))+" \cdot x + %s$"%str(latex(intercept)) G = points(pts,size=30,title=T) f = m*x+intercept G += plot(f,x,-2,5,color='green') show(G) 
       

                                
                            

                                
# This part for graphs to use with MC Math Coach pts = [(-2,4),(3,1)] G = points(pts,size=90,color='red') m = (1-4)/(3+2) b = 4-m*(-2) G += plot(m*x+b,(x,-3,5)) show(G) 
       
# This part for graphs to use with MC Math Coach m = (1-4)/(3+2) b = 4-m*(-2) pts = [(-2,4),(3,1),(1,m+b),(4,4*m+b)] G = points(pts,size=90,color='red') G += plot(m*x+b,(x,-3,5)) show(G) 
       
# This part for graphs to use with MC Math Coach m = (1-4)/(3+2) b = 4-m*(-2) pts = [(-2,4),(3,1),(1,3),(4,1)] G = points(pts,size=90,color='red') # G += plot(m*x+b,(x,-3,5)) show(G) 
       
# This interactive cell allows the user to repeatedly guess parameters for a line that seek to minimize the Total Squared Error # between the resulting line and the provided data points. This is included in the book text. var('x') @interact def _(Points = input_box([(-2,4),(3,1),(1,3),(4,1)]), m = slider(-4,4,0.05,1),b = slider(-2,4,0.05,1)): G = points(Points,size=20) xpt = [] ypt = [] f = m*x + b TSE = 0 for k in range(len(Points)): x0 = Points[k][0] xpt.append(x0) y0 = Points[k][1] ypt.append(y0) TSE += (f(x=x0) - y0)^2 G += line([(x0,f(x=x0)),(x0,y0)],color='orange') G += plot(f,x,min(xpt),max(xpt),color='gray') T = 'Total Squared Error = $%s$'%str(TSE) G.show(title = T) 
       

Click to the left again to hide and once more to show the dynamic interactive window