I am trying to create a Python function which will take x coordinates and y coordinates as an input and calculate the distances between all of the data points.
(我正在尝试创建一个Python函数,该函数将x坐标和y坐标作为输入并计算所有数据点之间的距离。)
The distances should be stored as a list (or array) and passed back to the calling program. (距离应存储为列表(或数组),并传递回调用程序。)
The algorithm I am starting with looks like the example below. (我开始使用的算法如下例所示。)
def distance(x, y):
dist = []
for j in range(len(x)):
for i in range(len(y)):
"""
Don't calculate the distance between the same point
since it will obviously be zero
"""
if j != i:
mag = (x[j] - x[i]) ** 2.0 + (y[j] - y[i]) ** 2.0
dist.append(np.sqrt(mag))
return dist
x_vals = [2.3, 3.6, 1.8]
y_vals = [1.6, 4.8, 2.8]
vals = distance(x_vals, y_vals)
print(vals)
This algorithm will calculate the distance between points 1-2, 1-3, 2-1, 2-3, 3-1, and 3-2, returning the following lists
(此算法将计算点1-2、1-3、2-1、2-3、3-1和3-2之间的距离,并返回以下列表)
[3.4539832078341086, 1.2999999999999996, 3.4539832078341086, 2.6907248094147422, 1.2999999999999996, 2.6907248094147422]
While the results are correct, the algorithm repeats measurements.
(当结果正确时,算法将重复测量。)
As you can see the distance from point 1-2 is the same as 2-1, and the distances between 1-3 is the same as 3-1, as well as 2-3 is the same as 3-2. (如您所见,到点1-2的距离与2-1相同,并且在1-3之间的距离与3-1相同,而在2-3处与3-2相同。)
In other words, I would like to create a more efficient algorithm that only calculates between 1-2, 1-3, and 2-3. (换句话说,我想创建一种仅在1-2、1-3和2-3之间进行计算的更有效的算法。)
While this sample only contains 3 data points (ie 3 pairs of x and y coordinates), I would like this algorithm to be applicable to a much larger number of datapoints, and be as efficient as possible since this could be applied to a large number of data points. (尽管此样本仅包含3个数据点(即3对x和y坐标),但我希望此算法适用于大量数据点,并应尽可能高效,因为它可以应用于大量数据点。数据点。)
ask by Jon translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…