2023-05-03 21:20:54 用Python写代码,模拟二维平面上的随机游走实验:起点坐标为(0,0),每次随机往前后左右四个方向移动一个单位。则: (1) 求出 n 次游走后,离起点最远的时候的坐标以及次数;(这里n 由输入的
时间: 2024-02-11 21:06:47 浏览: 19
数字确定) (2) 绘制出 n 次游走的轨迹图。
可以使用以下代码实现:
```python
import random
import matplotlib.pyplot as plt
def random_walk(n):
x, y = 0, 0
max_distance = 0
max_distance_step = 0
path = [(0, 0)]
for i in range(n):
direction = random.choice(['N', 'S', 'E', 'W'])
if direction == 'N':
y += 1
elif direction == 'S':
y -= 1
elif direction == 'E':
x += 1
else:
x -= 1
distance = x ** 2 + y ** 2
if distance > max_distance:
max_distance = distance
max_distance_step = i + 1
path.append((x, y))
return max_distance, max_distance_step, path
n = int(input("请输入游走次数: "))
max_distance, max_distance_step, path = random_walk(n)
print(f"离起点最远的时候的坐标为({path[max_distance_step][0]}, {path[max_distance_step][1]}),在第{max_distance_step}步达到")
print(f"离起点最远的距离为{max_distance}")
x, y = zip(*path)
plt.plot(x, y)
plt.title(f"{n}次游走轨迹图")
plt.xlabel("x")
plt.ylabel("y")
plt.show()
```
运行代码,输入游走次数,即可得到离起点最远的坐标和距离,同时绘制出轨迹图。