Share Pastebin
Guest
Public paste!

Untitled

By: a guest | Mar 17th, 2010 | Syntax: None | Size: 1.69 KB | Hits: 92 | Expires: Never
Copy text to clipboard
  1. from Graphics import *
  2.  
  3. def buildWindow():
  4.     """Build and scale a window for the regression program.
  5.     Include a small 'Done" box in the lower left"""
  6.     win=GraphWin("Regression",500,500)
  7.     win.setCoords(0,0,100,100)
  8.     # Create a 10x5 rectangle in the lower left corner
  9.     Rectangle(Point(0,0),Point(10,5)).draw(win)
  10.     Text((5,2.5),"Done").draw(win)
  11.     return win  # must return the handle to the created window.
  12.    
  13. def getAndPlotPoint(win):
  14.     """Get a mouse click in the window and draw a small circle at the
  15.     point where the mouse was clicked."""
  16.     p = win.getMouse()
  17.     Circle(p,.5).draw()
  18.     return Point(p)    #  return the point object
  19.    
  20. def gatherPointData(win):
  21.     """Gathers mouse clicks via calls to getAndPlotPoint.  Determines if
  22.     the click was in the 'Done' box.  If not, accumulate the statistics
  23.     needed to calculate the equation of the best fit straight line."""
  24.     n=sumX=sumY=sumX2=sumXY=0
  25.     while True:
  26.         p = GetAndPlotPoint(win)
  27.         x = p.getX()
  28.         y = p.getY()
  29.         if x > 10 and y > 5: break
  30.         sumX += X
  31.         sumY += y
  32.         sumX2 = x*x
  33.         sumXY += x*y
  34.         n += 1
  35.     return (n,sumX,sumY,sumX2,sumXY) # return a tuple with the stats
  36.  
  37. def main():
  38.     """Build a window, gather point data, compute the equation of the
  39.     best fit line and plot it.  Wait for mouse click before closing window."""
  40.     win = buildWindow()
  41.     n,sumX,sumY,sumX2,sumXY = gatherPointData(win)
  42.     m = (sumXY - sumX*sumY/n) / (sumX2 - sumX*sumX/n)
  43.     y1 = sumY/n + m*(0-sumX/n)
  44.     y2 = sumY/n + m*(100-sumX/n)
  45.     Line(Point(0,y1), Point(100,y2))
  46.     win.close()
  47.    
  48. if __name__ == "__main__":    
  49.     main()