Python – math.dist() 方法
Python中的数学模块包含许多数学运算,可以使用该模块轻松执行。 Python中的math.dist()
方法用于计算两点 p 和 q 之间的欧几里得距离,每个点都以坐标序列(或可迭代)的形式给出。这两个点必须具有相同的尺寸。
此方法是Python 3.8 版中的新方法。
Syntax: math.dist(p, q)
Parameters:
p: A sequence or iterable of coordinates representing first point
q: A sequence or iterable of coordinates representing second point
Returns: the calculated Euclidean distance between the given points.
代码 #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数学库