以下是基于 Python 的随机游走代码:

import random
import matplotlib.pyplot as plt

# 初始化位置为(0, 0)
x = 0
y = 0

# 初始化步长为1
step = 1

# 初始化步数为1000
num_steps = 1000

# 创建两个空列表,用于存储每个步骤的x和y坐标
x_values = [0]
y_values = [0]

# 随机生成移动方向
for i in range(num_steps):
    # 生成随机方向
    direction = random.choice(['N', 'S', 'W', 'E'])
    
    # 根据方向更新位置
    if direction == 'N':
        y += step
    elif direction == 'S':
        y -= step
    elif direction == 'W':
        x -= step
    else:
        x += step
        
    # 将新位置添加到列表中
    x_values.append(x)
    y_values.append(y)

# 绘制随机游走图像
plt.scatter(x_values, y_values, s=15)
plt.title('Random Walk')
plt.show()

这段代码用于生成 1000 个步骤的随机游走路径,并在图像上显示出来。在每一步中,程序随机选择一个方向(北、南、西或东),并更新当前位置。最终,程序将所有步骤的 x 和 y 坐标存储在列表中,并绘制出随机游走的路径。

Python 随机游走代码实现及可视化

原文地址: https://www.cveoy.top/t/topic/nsRw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录