从“如何像计算机科学家一样思考”课程中得到这个问题:
解释数据文件标签数据.txt使每一行包含一个x,y坐标对。编写一个名为plotRegression的函数,该函数从该文件中读取数据,并根据以下公式使用海龟绘制这些点和最佳拟合线:
y=y‘+m(x−x’
m=∑西仪−nx´y∑x2i−nx´2
http://interactivepython.org/runestone/static/thinkcspy/Files/Exercises.html?lastPosition=1308
我的代码似乎不起作用,我不知道为什么。看起来python将数据解释为str而不是float。在
def plotregression(t):
labfile = open('labdata.txt','r')
sumx = 0
sumy = 0
count = 0
sumprod = 0
sumsqrx =0
sumsqrnx = 0
for i in labfile:
points = i.split()
print (points)
t.up()
t.setpos(points[0],points[1])
t.stamp()
sumx = sumx + int(points[0])
sumy = sumy + int(points[1])
prod = points[0]*int(points[1])
sumprod = sumprod + prod
count += 1
sqrx = int(points[0])**2
sumsqrx = sumsqrx + sqrx
sqrnx = int(points[0])**(-2)
sumsqrnx = sumsqrnx + sqrnx
avgx = sumx/count
avgy = sumy/count
m = (sumprod - count(avgx*avgy))/sumsqrx- (count(avgx**2))
print(m)
for bestline in labfile:
line = bestline.split()
y= avgy + m(int(line[0])-avgx)
t.down()
t.setpos(0,0)
t.setpos(line[0],y)
plotregression(kj)
感谢你的帮助。在
Thnx公司
实际上,我自己解决了这个问题,它终于像我告诉它的那样做了。但我很想知道我是否可以删去任何不必要的代码行。我觉得它有点太长了,我错过了一些可以让它更简单的方法。在
如果我能在任何地方砍柴,请告诉我
我用交互式python解决了同样的问题。这是我怎么做到的。在
我晚了5年左右,但这是我的两分钱。在
问题可能出在以下方面: t.setpos(点[0],点[1]) 这是告诉海龟转到点[0]和点[1]的字符串值。 例如,如果点[0]存储值“50”,而点[1]保存值“60”,则“50”+“60”将返回字符串“5060”
这条线也可能有问题: prod=points[0]*int(点[1]) 这是将点[0]中的字符串值与点[1]中的整数值相加 在这种情况下,使用前面的值points[0]将是“50”,int(points[1])将是60。那是60而不是“60”。所以不能将字符串“50”与整数60相加。在
我是如何解决这个问题的:
我不知道这是不是正确的坡度,但似乎是在正确的方向。希望这能帮助那些有同样问题的人。在
相关问题 更多 >
编程相关推荐