根据提示,在右侧编辑器补充代码,完善一维随机游走程序,使得向右移动的概率为 r,向左移动的概率为 1-r(生成中的数字,而不是{1,2}中的整数)。在 n s 步后计算 n p 个粒子的平均位置。 在数学上可以证明,在n p →∞时,平均位置逼近rn s −(1−r)n s (n s 是步数)。 请你编写函数 random_walk1D_drift(np, ns, r),返回 np 个粒子随机游走 ns 步(每步右移概率为 r)后平均位置的估算值。
时间: 2024-02-13 12:07:18 浏览: 31
```python
import numpy as np
def random_walk1D_drift(np, ns, r):
positions = np.zeros(np) # 初始化粒子位置数组
for i in range(ns):
moves = np.random.random(np) # 生成每个粒子的移动随机数
for j in range(np):
if moves[j] < r: # 如果随机数小于 r,粒子向右移动
positions[j] += 1
else: # 否则粒子向左移动
positions[j] -= 1
average_position = np.mean(positions) # 计算平均位置
return average_position
```
其中,np 是粒子数目,ns 是步数,r 是向右移动的概率。该函数首先初始化粒子位置数组 positions,然后在每一步中,生成每个粒子的移动随机数 moves,如果随机数小于 r,粒子向右移动一步,否则粒子向左移动一步。最后计算粒子平均位置并返回。
相关问题
本关任务:编写一个程序,实现带漂移的一维随机游走。 相关知识 为了完成本关任务,你需要掌握: 1.常见 Python 随机数函数; 2.随机游走(random walk)。 常见Python随机数函数 import random r = random.random() [0, 1) 实数 r = random.uniform(a, b) [a, b) 实数 i = random.randint(a, b) [a, b] 整数 随机游走(random walk) 也称随机漫步,是指基于过去的表现,无法预测将来的发展步骤和方向。其概念接近于布朗运动,是布朗运动的理想数学状态。醉汉行走的轨迹、布朗运动、股票的涨跌等行为都可用随机游走来模拟。 编程要求 根据提示,在右侧编辑器补充代码,完善一维随机游走程序,使得向右移动的概率为 r,向左移动的概率为 1-r(生成中的数字,而不是{1,2}中的整数)。在 n s 步后计算 n p 个粒子的平均位置。 在数学上可以证明,在n p →∞时,平均位置逼近rn s −(1−r)n s (n s 是步数)。 请你编写函数 random_walk1D_drift(np, ns, r),返回 np 个粒子随机游走 ns 步(每步右移概率为 r)后平均位置的估算值。
# 完善以下代码
import random
def random_walk1D_drift(np, ns, r):
total_pos = 0 # 总位置
for i in range(np):
pos = 0 # 单个粒子位置
for j in range(ns):
if random.random() < r:
pos += 1
else:
pos -= 1
total_pos += pos
return total_pos / np
# 测试代码
print(random_walk1D_drift(10000, 100, 0.5))
编程要求 根据提示,在右侧编辑器补充代码,完善一维随机游走程序,使得向右移动的概率为 r,向左移动的概率为 1-r(生成中的数字,而不是{1,2}中的整数)。在 n s 步后计算 n p 个粒子的平均位置。 在数学上可以证明,在n p →∞时,平均位置逼近rn s −(1−r)n s (n s 是步数)。 请你编写函数 random_walk1D_drift(np, ns, r),返回 np 个粒子随机游走 ns 步(每步右移概率为 r)后平均位置的估算值import random random.seed(10) def random_walk1D_drift(np, ns, r): #---------begin----------- #---------end----------- np = 1000 # 粒子数量 for r in [0.3, 0.7]: # 右移概率 for ns in [100, 200]: # 步数 m=random_walk1D_drift(np, ns, r) # 打印结果 print('粒子理论位置: %.5f' %(r*ns-(1-r)*ns)) print('粒子实际平均位置: %.5f' %(m))
import random
def random_walk1D_drift(np, ns, r):
total_pos = 0
for i in range(np):
pos = 0
for j in range(ns):
if random.random() < r:
pos += 1
else:
pos -= 1
total_pos += pos
return total_pos/np
np = 1000 # 粒子数量
for r in [0.3, 0.7]: # 右移概率
for ns in [100, 200]: # 步数
m=random_walk1D_drift(np, ns, r)
# 打印结果
print('粒子理论位置: %.5f' %(r*ns-(1-r)*ns))
print('粒子实际平均位置: %.5f' %(m))
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)