用python实现空间中两点之间的距离
时间: 2024-10-22 10:06:51 浏览: 23
空间两点间的距离pta的python和java示例
在Python中,你可以使用欧几里得距离公式来计算两个点在二维或三维空间中的距离。对于二维空间,如果你有两个点A(x1, y1)和B(x2, y2),距离d可以这样计算:
```python
import math
def distance_2d(point_A, point_B):
x1, y1 = point_A
x2, y2 = point_B
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
# 示例
point_A = (1, 2)
point_B = (4, 6)
print(distance_2d(point_A, point_B))
```
对于三维空间,只需将公式稍作修改,添加第三个维度z:
```python
def distance_3d(point_A, point_B):
x1, y1, z1 = point_A
x2, y2, z2 = point_B
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2 + (z2 - z1)**2)
# 示例
point_A = (1, 2, 3)
point_B = (4, 5, 7)
print(distance_3d(point_A, point_B))
```
阅读全文