Untitled
By: a guest | Mar 17th, 2010 | Syntax:
None | Size: 1.69 KB | Hits: 92 | Expires: Never
from Graphics import *
def buildWindow():
"""Build and scale a window for the regression program.
Include a small 'Done" box in the lower left"""
win=GraphWin("Regression",500,500)
win.setCoords(0,0,100,100)
# Create a 10x5 rectangle in the lower left corner
Rectangle(Point(0,0),Point(10,5)).draw(win)
Text((5,2.5),"Done").draw(win)
return win # must return the handle to the created window.
def getAndPlotPoint(win):
"""Get a mouse click in the window and draw a small circle at the
point where the mouse was clicked."""
p = win.getMouse()
Circle(p,.5).draw()
return Point(p) # return the point object
def gatherPointData(win):
"""Gathers mouse clicks via calls to getAndPlotPoint. Determines if
the click was in the 'Done' box. If not, accumulate the statistics
needed to calculate the equation of the best fit straight line."""
n=sumX=sumY=sumX2=sumXY=0
while True:
p = GetAndPlotPoint(win)
x = p.getX()
y = p.getY()
if x > 10 and y > 5: break
sumX += X
sumY += y
sumX2 = x*x
sumXY += x*y
n += 1
return (n,sumX,sumY,sumX2,sumXY) # return a tuple with the stats
def main():
"""Build a window, gather point data, compute the equation of the
best fit line and plot it. Wait for mouse click before closing window."""
win = buildWindow()
n,sumX,sumY,sumX2,sumXY = gatherPointData(win)
m = (sumXY - sumX*sumY/n) / (sumX2 - sumX*sumX/n)
y1 = sumY/n + m*(0-sumX/n)
y2 = sumY/n + m*(100-sumX/n)
Line(Point(0,y1), Point(100,y2))
win.close()
if __name__ == "__main__":
main()