【问题标题】:Simple random walk简单的随机游走
【发布时间】:2014-05-23 15:56:45
【问题描述】:

我无法生成类似于我在电子表格中使用的简单随机游走路径。如何编写代码,以便将每个步骤添加到上一步,以保持显示距离零的“运行总计”?从零开始,加上一步,加上一步,减去一步将等于 +1 (0+1+1-1)。当然使用随机选择。

另外,有没有办法用 Python3.4 绘制这个图表?

import random

a = 0

trials = input('Trails : ')

while a < int(trials):

    a = a + 1                  # Simple step counter
    x = random.randint(-1,1)   # Step direction (-1, 0, +1)

    print(a,x)                 # Prints numbered list of steps and direction

【问题讨论】:

    标签: python random


    【解决方案1】:

    应该这样做(即保持运行总计) - 至于绘图 - 您可能需要将每个步骤的总计保留在列表中并使用另一个库 - 例如 matplotlib 来绘制结果。

    import random
    
    a = 0
    total = 0 # Keep track of the total 
    
    trials = input('Trails : ')
    
    while a < int(trials):
    
        a = a + 1                  # Simple step counter
        x = random.randint(-1,1)   # Step direction (-1, 0, +1)
        total += x                 # Add this step to the total
    
        print(a,x, total)          # Prints numbered list of steps and direction
    

    【讨论】:

      【解决方案2】:

      可以使用np.cumsum(np.random.randint(-1,2,10)) 计算作为随机步数函数的位置。您可以将其绘制为步数的函数

      import numpy as np
      import matplotlib.pyplot as plt
      
      increment = np.random.randint(-1,2,10)
      position = np.cumsum(increment)
      plt.plot(np.arange(1, position.shape[0]+1), position)
      plt.show()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-29
        相关资源
        最近更新 更多