一维随机游走程序,使得向右移动的概率为 r,向左移动的概率为 1-r(生成中的数字,而不是{1,2}中的整数)。在 n s 步后计算 n p 个粒子的平均位置
时间: 2023-07-16 16:14:11 浏览: 51
以下是一维随机游走程序的Python代码:
```
import random
def random_walk(n, r, np):
"""
n: number of steps
r: probability of moving right
np: number of particles
"""
positions = [0] * np # initialize particle positions to 0
for i in range(n): # for each step
for j in range(np): # for each particle
if random.random() < r: # move right with probability r
positions[j] += 1
else: # move left with probability 1-r
positions[j] -= 1
return sum(positions) / np # calculate average position of particles
```
可以通过调用该函数来计算 n 步后 n_p 个粒子的平均位置:
```
avg_position = random_walk(n, r, np)
print("Average position after {} steps with {} particles: {}".format(n, np, avg_position))
```
其中,n、r 和 np 分别为步数、向右移动的概率和粒子数。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)