【发布时间】:2016-07-23 11:16:57
【问题描述】:
我正在尝试使用 numpy 对笛卡尔网格上的 100 个随机点在 x 和 y 轴上的 0 - 100 之间的值之间使用简单的近似值来解决旅行商问题方法。
我创建了各种唯一的整数并填满了三个列表:
xList = [np.round(np.random.rand()*100)] #Generates random x,y coordinates
yList = [np.round(np.random.rand()*100)]
orderList = [np.round(np.random.rand()*100)]
我已经定义了一个函数,它将找到笛卡尔平面上两点之间的最短距离:
def distance(x1, x2, y1, y2):
return np.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2))
然后,如果特定路径在点之间随机移动,我会遍历此列表以找到总长度:
totalLength = 0
for i in range(0, 98):
stuff = distance(int(xList[orderList[i]]), int(xList[orderList[i+1]]), int(yList[orderList[i]]), int(yList[orderList[i+1]]))
totalLength = totalLength + stuff
shortestLength = totalLength
对于我的预定义函数获取消息来说,打字似乎是个问题:
stuff = distance(int(xList[orderList[i]]), int(xList[orderList[i+1]]), int(yList[orderList[i]]), int(yList[orderList[i+1]]))***
TypeError: list indices must be integers, not numpy.float64
我不知道如何在 python 中正确定义类型,所以我想要一些关于将 float.numpy64 类型转换为整数或允许我的预定义函数适用于正确类型的建议。
【问题讨论】:
-
您可能希望将
np.hypot用于distance。