Random walk's weird outcome in python 3?

前端 未结 1 798
执念已碎
执念已碎 2021-01-17 06:41

I just start learning python and have a problem to print a new location of random walk in 3 dimensions. There is no error popping up, but it\'s obvious that the output (x, y

相关标签:
1条回答
  • 2021-01-17 07:18

    You set n to a new random number in every if test:

    if n < 1/6:
        x = x + 1           # move east
        n = random.random() # generate a new random number
    

    This means the next if test can then also match on the new n, giving you more than one change per step.

    Move the n = random.random() step to the top of the loop, generating it only once per step. You probably want to use elif as well to avoid making too many tests:

    N = 30  # number of steps
    
    x = 0
    y = 0
    z = 0
    
    for count in range(N):
        n = random.random() # generate a new random number
        if n < 1/6:
            x = x + 1           # move east
        elif n < 2/6:
            y = y + 1           # move north
        elif n < 3/6:
            z = z + 1           # move up
        elif n < 4/6:
            x = x - 1           # move west
        elif n < 5/6:
            y = y - 1           # move south
        else:
            z = z - 1           # move down
    
        print("(%d,%d,%d)" % (x,y,z)) 
    

    I also switched to using a for loop over range() so you don't have to manually increment and test count.

    This can be further simplified by using a list to store the directions, random.range() to pick an index in that list at random, and random.choice() to pick what direction to change the step in:

    N = 30  # number of steps
    
    pos = [0, 0, 0]
    
    for count in range(N):
        index = random.randrange(3) # generate a new random index
        change = random.choice([-1, 1])
        pos[index] += change
    
        print(tuple(pos))
    
    0 讨论(0)
提交回复
热议问题