在坐标系中计算两点间的距离,我们通常使用欧几里得距离公式。这个公式基于直角三角形的性质,其中两个点 A 和 B 的坐标分别是 (x1, y1) 和 (x2, y2),那么这两点之间的距离 d 可以通过以下公式计算:
- d = sqrt((x2
- x1)^2 + (y2 - y1)^2)
这个公式中的平方根是开方运算,因此它表示的是两点之间的直线距离。
算法实现步骤
1. 定义函数
首先,我们需要定义一个函数来计算两点之间的距离。这个函数接受两个参数,即点的坐标。
```python
def calculate_distance(point1, point2):
- return math.sqrt((point2[0]
- point1[0])2 + (point2[1] - point1[1])2)
```
2. 输入数据
接下来,我们需要输入两个点的坐标。
```python
point1 = (3, 4)
point2 = (6, 8)
```
3. 调用函数
最后,我们调用上面定义的函数来计算这两个点之间的距离。
```python
distance = calculate_distance(point1, point2)
print(f"The distance between the two points is: {distance}")
```
4. 测试代码
为了确保我们的函数能够正确计算两点之间的距离,我们可以运行一些测试用例。
```python
# 测试用例
point1 = (3, 4)
point2 = (6, 8)
point3 = (9, 12)
point4 = (1, 2)
# 预期结果
expected_distance1 = 5.0
expected_distance2 = 13.0
expected_distance3 = 15.0
expected_distance4 = 5.0
# 实际结果
distance1 = calculate_distance(point1, point2)
distance2 = calculate_distance(point3, point4)
distance3 = calculate_distance(point4, point1)
distance4 = calculate_distance(point4, point3)
# 输出结果
print(f"Expected distance for point1 and point2: {expected_distance1}")
print(f"Expected distance for point3 and point4: {expected_distance3}")
print(f"Expected distance for point4 and point1: {expected_distance4}")
print(f"Distance for point1 and point2: {distance1}")
print(f"Distance for point3 and point4: {distance2}")
print(f"Distance for point4 and point3: {distance3}")
```
通过运行上述代码,我们可以验证我们的函数是否正确地计算了两点之间的距离。如果所有的预期结果都与实际结果相匹配,那么我们可以认为我们的函数是正确的。