2014-05-23 104 views
0

我无法生成类似于我在电子表格中使用的简单随机漫步路径。如何编写代码,以便每个步骤都添加到上一步中,以保持显示与零距离的“运行总计”?从零开始,加上一步,再加上一步,减一步就等于+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 

回答

2

这应该这样做(即保持一个运行总计) - 作为绘图 - 你可能需要保持总在列表中的每一步,并使用另一个库 - 如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 
0

作为随机步数的函数的位置可以用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()