如何使用Python为生成的随机坐标点计算并构建欧氏距离矩阵
纯Python无依赖实现方案
无需安装额外第三方库,直接在你现有代码基础上补充距离计算和表格输出逻辑即可:
import random import math npoints = int(input("Type the npoints:")) width = float(input("Enter the Width you want:")) height = float(input("Enter the Height you want:")) # 生成随机点,保留你原有逻辑 sample = [] for _ in range(npoints): sample.append((width * random.random(), height * random.random())) print("生成的随机点:", *[f"({w:.2f}, {h:.2f})" for w, h in sample], sep=', ') # 初始化n*n距离矩阵,对角线默认值为0(点到自身的距离) dist_matrix = [[0.0 for _ in range(npoints)] for _ in range(npoints)] # 利用矩阵对称性计算上三角和下三角,减少一半计算量 for i in range(npoints): x1, y1 = sample[i] for j in range(i + 1, npoints): x2, y2 = sample[j] # 欧氏距离计算 dist = math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) dist_matrix[i][j] = dist_matrix[j][i] = round(dist, 2) # 表格格式输出 print("\n欧氏距离矩阵:") # 打印表头 print(f"{'':<5}", end="") for col in range(npoints): print(f"P{col:<6}", end="") print() # 打印每行数据 for row in range(npoints): print(f"P{row:<4}", end="") for val in dist_matrix[row]: print(f"{val:<7.2f}", end="") print()
运行示例
对应你给出的4个点输入,输出效果如下:
Type the npoints:4 Enter the Width you want:10 Enter the Height you want:10 生成的随机点:, (8.52, 3.73), (9.69, 6.87), (8.20, 6.14), (4.18, 0.76) 欧氏距离矩阵: P0 P1 P2 P3 P0 0.00 3.33 2.42 5.19 P1 3.33 0.00 1.63 8.24 P2 2.42 1.63 0.00 6.72 P3 5.19 8.24 6.72 0.00
高效实现方案(适合点数量较多的场景)
如果需要处理大量点,可使用scipy的内置距离计算接口,性能远高于纯Python循环,使用前先执行pip install scipy安装依赖:
import random from scipy.spatial.distance import pdist, squareform npoints = int(input("Type the npoints:")) width = float(input("Enter the Width you want:")) height = float(input("Enter the Height you want:")) sample = [] for _ in range(npoints): sample.append((width * random.random(), height * random.random())) print("生成的随机点:", *[f"({w:.2f}, {h:.2f})" for w, h in sample], sep=', ') # 一行代码生成距离矩阵 dist_matrix = squareform(pdist(sample, metric="euclidean")).round(2) # 输出逻辑和纯Python版本一致 print("\n欧氏距离矩阵:") print(f"{'':<5}", end="") for col in range(npoints): print(f"P{col:<6}", end="") print() for row in range(npoints): print(f"P{row:<4}", end="") for val in dist_matrix[row]: print(f"{val:<7.2f}", end="") print()
内容的提问来源于stack exchange,提问作者user16726326
相关产品推荐
相关产品推荐

