我撰寫了一個代碼,可以在坐標系中的某個寬度和長度范圍內生成所需數量的點。如何計算和制表我使用歐幾里得方法生成的這些點的距離矩陣?
import random
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=', ')
輸出是:
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)
Process finished with exit code 0
如何創建具有 rondom 點的距離矩陣,如下例所示:


非常感謝您的幫助。
uj5u.com熱心網友回復:
如果要使用外部模塊,scipy對于矩陣計算非常有效。
import random
import pandas as pd
from scipy.spatial import distance
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=', ')
#Create a matrix from these points
mat_dist = distance.cdist(sample, sample, 'euclidean')
df_mat_dist = pd.DataFrame(mat_dist)
print(df_mat_dist)
輸出
Type the npoints:4
Enter the Width you want:10
Enter the Height you want:10
(8.89, 8.85), (9.00, 9.43), (9.67, 9.45), (3.96, 5.68)
0 1 2 3
0 0.000000 0.584322 0.985072 5.856736
1 0.584322 0.000000 0.669935 6.277323
2 0.985072 0.669935 0.000000 6.839240
3 5.856736 6.277323 6.839240 0.000000
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/368684.html
上一篇:從嵌套字典中列印兩位數
下一篇:從檔案內容讀取和執行操作
