You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何不使用循环实现一组二维点之间的距离计算

无循环实现二维点集两两欧氏距离计算

实现思路

利用数值计算库的向量化广播特性替代显式循环,全程所有运算调用底层优化过的向量操作,不需要手写任何循环语句,同时计算效率远高于自定义循环。
假设输入点集是形状为(N, 2)的数组,每一行对应一个二维点的(x, y)坐标,最终输出为(N, N)的距离矩阵,其中dist_mat[i][j]即为第i个点和第j个点的欧氏距离,对应公式:
distance_between_points = sqrt((x2 - x1)^2 + (y2 - y1)^2)

代码实现(Python + Numpy)

import numpy as np

def calc_pairwise_euclidean_dist(points: np.ndarray) -> np.ndarray:
    # 拆分x、y分量,调整维度适配广播规则
    x_coords = points[:, 0, np.newaxis]
    y_coords = points[:, 1, np.newaxis]
    # 向量化计算所有点对的距离,无显式循环
    dist_matrix = np.sqrt((x_coords - x_coords.T) ** 2 + (y_coords - y_coords.T) ** 2)
    return dist_matrix

测试示例

# 构造3个二维点的测试点集
test_points = np.array([[0, 0], [1, 0], [0, 1]])
print(calc_pairwise_euclidean_dist(test_points))

输出结果

[[0.         1.         1.        ]
 [1.         0.         1.41421356]
 [1.         1.41421356 0.        ]]

该方案全程无任何for/while循环,所有运算由Numpy底层完成,支持大数量级点集的快速计算。

内容的提问来源于stack exchange,提问作者MathMath

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 13:18:04