【问题标题】:Python, distance between two points type issuePython,两点之间的距离类型问题
【发布时间】: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

标签: python list numpy types


【解决方案1】:

numpy.round 不会产生整数:

> print(type(np.round(13.4)))
<type 'numpy.float64'>

可能的解决方案:

> int(np.round(13.4))
13 # type int
> np.int(13.4)
13 # type int
> math.trunc(13.4)
13 # type int

考虑对您的代码进行以下重新表述:

import numpy as np
import random
import scipy.spatial.distance as distance

points = np.rollaxis(np.random.randn(2, 100), 1)
indices = range(points.size)

# distance.euclidean(points[5], points[10])

【讨论】:

  • stuff = distance(int(np.round(xList[orderList[i]])), int(np.round(xList[orderList[i+1]])), int(np.round(yList[orderList[i]])), int(np.round(yList[orderList[i+1]]))) TypeError: 列表索引必须是整数,而不是 numpy.float64
  • 问题是orderList的元素。这些必须是整数。
【解决方案2】:

您的orderList 应该是整数的numpy 数组(或普通的Python 列表),而不是随机浮点数。

我假设它应该是一个 0 - 100 范围内的数字随机列表。您可以像这样在纯 Python 中构造这样一个列表:

import random

listsize = 10
orderList = list(range(listsize))
random.shuffle(orderList)
print(orderList)    

典型输出

[6, 5, 1, 2, 0, 4, 9, 3, 7, 8]

(我已将 listsize 设置为 10 以保持输出较小)。

您还可以将 Numpy 数组传递给random.shuffle

import random
import numpy as np

listsize = 10
orderList = np.arange(listsize)
random.shuffle(orderList)
print(orderList)        

典型输出

[6 9 0 1 3 7 2 5 8 4]

这个orderList的元素的dtype是int32。

其实Numpy有自己的random.shuffle函数,所以可以把之前sn-p中的random.shuffle(orderList)替换成

np.random.shuffle(orderList)

【讨论】:

    猜你喜欢
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    • 2012-07-17
    • 1970-01-01
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    相关资源
    最近更新 更多