简体   繁体   English

如何使用在Python中执行一维随机游走的随机数?

[英]How to use random numbers that executes a one dimensional random walk in python?

Start with a one dimensional space of length m, where m = 2 * n + 1. Take a step either to the left or to the right at random, with equal probability. 从长度为m的一维空间开始,其中m = 2 * n +1。以等概率随机向左或向右迈出一步。 Continue taking random steps until you go off one edge of the space, for which I'm using while 0 <= position < m. 继续采取随机步骤,直到离开该空间的某一边缘为止,我正在使用该边缘,而0 <= position <m。

We have to write a program that executes the random walk. 我们必须编写一个执行随机游走的程序。 We have to create a 1D space using size n = 5 and place the marker in the middle. 我们必须使用大小n = 5创建一维空间,并将标记放置在中间。 Every step, move it either to the left or to the right using the random number generator. 每一步,使用随机数生成器将其向左或向右移动。 There should be an equal probability that it moves in either direction. 它朝两个方向移动的可能性均应相等。

I have an idea for the plan but do not know how to write it in python: 我对计划有一个想法,但不知道如何用python编写它:

  • Initialize n = 1, m = 2n + 1, and j = n + 1. 初始化n = 1,m = 2n + 1,和j = n + 1。
  • Loop until j = 0 or j = m + 1 as shown. 如图所示,循环直到j = 0或j = m +1。 At each step: 在每一步:
    • Move j left or right at random. 左右随机移动j。
    • Display the current state of the walk, as shown. 显示步行的当前状态,如图所示。
  • Make another variable to count the total number of steps. 设置另一个变量以计算步骤总数。
    • Initialize this variable to zero before the loop. 在循环之前将此变量初始化为零。
    • However j moves always increase the step count. 但是,j动作始终会增加步数。
  • After the loop ends, report the total steps. 循环结束后,报告全部步骤。
  • 1 - Start with a list initialized with 5 items (maybe None ?) 1-从以5项初始化的列表开始(也许None ?)
  • 2 - place the walker at index 2 2-将助行器放在索引2处
  • 3 - randomly chose a direction (-1 or + 1) 3-随机选择一个方向(-1或+ 1)
  • 4 - move the walker in the chosen direction 4-在选择的方向上移动助步器
  • 5 - maybe print the space and mark the location of the walker 5-也许打印空间并标记助行器的位置
  • 6 - repeat at step 3 as many times as needed 6-根据需要在步骤3重复多次

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM