numpy学习笔记14:模拟随机游走过程(一次实验)
随机游走是一个对象在离散时间步中的随机移动,每次移动的方向和步长由概率决定。在用户提供的代码中,步长数组`steps`的每个元素是-1或1,代表向左或向右移动一步。`np.random.choice`的作用就是生成这样的随机步长序列。
随机游走是一种数学统计模型,其中的每一步方向和大小都是随机的。下面使用 NumPy 模拟一维和二维的随机游走过程:
1.代码示例
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
def simulate_1d_random_walk(num_steps):
"""
模拟一维随机游走
:param num_steps: 游走的步数
:return: 一维随机游走的位置数组
"""
steps = np.random.choice([-1, 1], size=num_steps)
positions = np.cumsum(steps)
return positions
def simulate_2d_random_walk(num_steps):
"""
模拟二维随机游走
:param num_steps: 游走的步数
:return: 二维随机游走的 x 和 y 坐标数组
"""
steps_x = np.random.choice([-1, 1], size=num_steps)
steps_y = np.random.choice([-1, 1], size=num_steps)
positions_x = np.cumsum(steps_x)
positions_y = np.cumsum(steps_y)
return positions_x, position

最低0.47元/天 解锁文章
1919

被折叠的 条评论
为什么被折叠?



