# ShowLS.py # Name # Date """ Illustrates a method that can be used to fit a line to data. """ from random import normalvariate as randn from random import uniform as randu from simpleGraphicsE import * def Mult(x,y): """ Returns a list with the property that each element is the product of the corresponding elements in x and y. Thus, Mult([2,3,4],[5,6,7]) returns [10,18,28]. PreC: x and y are float lists that have the same length. """ pass def Shift(x,a): """ Returns a list obtained by subtracting a from each element of x. Thus, Shift([5,6,7],2) returns [3,4,5]. PreC: x and y are float lists that have the same length. """ pass """ !!!!!!!!!!!!!!!!!! For full credit, your implementation of LSFit must make effective use of the functions Mult and Shift. !!!!!!!!!!!!!!!!!! """ def LSFit(x,y): """ Returns floats a and b so that a + b*x[k] is approximately y[k]. PreC: x and y are float lists. x has distinct elements. """ pass # Application Script if __name__ == '__main__': sigma = input('Enter the amount of noise: ') # Window size M = 5 # Number of points n = 50 # Generate a cloud of points that is linear but with # noise specified by sigma. y1 = randu(-M,M) y2 = randu(-M,M) # The "true" a and b... aExact = (y2-y1)/2; bExact = (y2-y1)/(2*M) x = [] y = [] h = float(2*M)/(n-1) for k in range(n): xVal = -M+k*h yVal = (aExact + bExact*xVal) + randn(0,sigma) x.append(xVal) y.append(yVal) # Fit the data and display [a,b] = LSFit(x,y) MakeWindow(M,bgcolor=BLACK,labels=False) # x and y axes.. Connect(-M,0,M,0,linecolor=YELLOW) Connect(0,-M,0,M,linecolor=YELLOW) # The noisy data... DrawPoints(x,y,.1,ORANGE) # Draw the fitting line Connect(-M,a-b*M,M,a+b*M,linecolor=CYAN) ShowWindow()