當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python math.dist()用法及代碼示例


數學模塊Python中的Math庫包含許多數學運算,可以使用該模塊輕鬆執行。math.dist()Python中的方法用於計算兩個點p和q之間的歐幾裏得距離,每個點以坐標序列(或可迭代)給出。這兩個點必須具有相同的尺寸。此方法是Python版本3.8中的新增函數。

用法: math.dist(p, q)

參數:
p:代表第一個點的坐標序列或可迭代
q:代表第二點的坐標序列或可迭代


返回:計算出的給定點之間的歐幾裏得距離。

代碼1:用於math.dist()方法

# Python Program to explain math.dist() method 
  
# Importing math module 
import math 
  
# One dimensional Point 
  
# Coordinate of Point P 
P = 3
  
# Coordinates of point Q 
Q = -8
  
# Calculate the Euclidean distance  
# between points P and Q 
eDistance = math.dist([P], [Q]) 
print(eDistance)
輸出:
11.0

代碼2:

# Python Program to explain math.dist() method 
  
# Importing math module 
import math 
  
# Two dimensional Point 
  
# Coordinates of Point P 
Px = 3 
Py = 7
  
# Coordinates of point Q 
Qx = -5
Qy = -9
  
# Calculate the Euclidean distance  
# between points P and Q 
eDistance = math.dist([Px, Py], [Qx, Qy]) 
print(eDistance) 
  
  
# Three-dimensional point 
  
# Coordinates of Point P 
P = [3, 6, 9] 
  
# Coordinates of point Q 
Q = [1, 0, -2]  
  
# Calculate the Euclidean distance  
# between points P and Q 
eDistance = math.dist(P, Q) 
print(eDistance)
輸出:
17.88854381999832
12.688577540449518

代碼3:

# Python Program to explain math.dist() method 
  
# Importing math module 
import math 
  
# n-dimensional Point 
  
# Coordinates of Point P 
P = [3, 9, 7, 2, 4, 5]  
  
# Coordinates of point Q 
Q = [-5, -3, -9, 0, 6, 2] 
  
# Calculate the Euclidean distance  
# between points P and Q 
eDistance = math.dist(P, Q) 
print(eDistance) 
  
# Dimension of both points  
# should be the same 
輸出:
21.93171219946131

參考: Python math library



相關用法


注:本文由純淨天空篩選整理自ihritik大神的英文原創作品 Python – math.dist() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。