0

我正在尝试在 python 中使用random.random().

def takeStep(prevPosition, maxStep):

    """simulates taking a step between positive and negative maxStep, \
adds it to prevPosition and returns next position"""

    nextPosition = prevPosition + (-maxStep + \
                     ( maxStep - (-maxStep)) * random.random())

list500Steps = []

list1000Walks = []

for kk in range(0,1000):

    list1000Walks.append(list500Steps)


    for jj in range(0 , 500):

        list500Steps.append(list500Steps[-1] + takeStep(0 , MAX_STEP_SIZE))

我知道为什么这给了我它的作用,只是不知道该怎么做。请给出最简单的答案,在这个新的并且还不知道很多。

4

2 回答 2

1
for kk in xrange(0,1000):
    list500steps = []
    for jj in range(0,500):
         list500steps.append(...)
    list1000walks.append(list500steps)

请注意我是如何在第一个 for 循环中每次创建一个空数组 (list500steps) 的?然后,在创建所有步骤之后,我将该数组(现在不是空的)附加到步行数组中。

于 2013-03-05T03:21:54.457 回答
0
 import random

 def takeStep(prevPosition, maxStep):

     """simulates taking a step between positive and negative maxStep, \
      adds it to prevPosition and returns next position"""

      nextPosition = prevPosition + (-maxStep + \
      ( maxStep - (-maxStep)) * random.random())
       return nextPosition # You didn't have this, I'm not exactly sure what you were going for         #but I think this is it
#Without this statement it will repeatedly crash

list500Steps = [0] 
list1000Walks = [0]
#The zeros are place holders so for the for loop (jj) below. That way 
#The first time it goes through the for loop it has something to index-
#during "list500Steps.append(list500Steps[-1] <-- that will draw an eror without anything
#in the loops. I don't know if that was your problem but it isn't good either way



for kk in range(0,1000):
    list1000Walks.append(list500Steps)


for jj in range(0 , 500):
    list500Steps.append(list500Steps[-1] + takeStep(0 , MAX_STEP_SIZE)) 
 #I hope for MAX_STEP_SIZE you intend on (a) defining the variable (b) inputing in a number 

您可能想要打印其中一个列表来检查输入。

于 2013-03-05T03:49:08.200 回答