约束 python 中的随机游走,如何使其工作?

Constraining a Random Walk in python, how to make it work?

这是我编写的随机游走代码,我试图限制其中 -5 < y < 5:

import random
import numpy as np
import matplotlib.pyplot as plt
import math
import decimal

def dirs(x):
  return np.array( [math.cos(x), math.sin(x)] )

def constrainedRandomWalk(x):
  numSteps = x
  locations = np.zeros( (numSteps, 2) ) 
  for i in range(1, numSteps):
    r = random.randrange(628318)/100000  
    move = dirs(r)        
    locations[i] = locations[i-1] + move
    if -5<locations[i][1]<5:
      continue
  #return locations

  plt.figure(figsize=(8,8))
  plt.plot( locations[:,0], locations[:,1], alpha=0.7 );
  plt.xlim([-20,20])
  plt.ylim([-20,20])

我试图通过在循环上设置一个条件来限制“步行角色”

 if -5<locations[i][1]<5:
      continue

然而,正如您在这里看到的,角色离开了 -5

谁能告诉我如何实际约束随机游走以及为什么这种方法不起作用?谢谢!

您正在更新 locations,然后再测试移动是否有效:

import math
import random

import matplotlib.pyplot as plt
import numpy as np


def dirs(x):
    return np.array([math.cos(x), math.sin(x)])


def constrained_random_walk(num_steps):
    # Specify Start Point
    locations = [np.array([0, 0])]
    # Go Until locations is long enough
    while len(locations) < num_steps:
        r = random.randrange(628318) / 100000
        move = dirs(r)
        # Test if the new move is in bounds first
        new_location = locations[-1] + move
        if -5 < new_location[1] < 5:
            locations.append(new_location)

    locations = np.array(locations)
    plt.figure(figsize=(8, 8))
    plt.plot(locations[:, 0], locations[:, 1], alpha=0.7)
    plt.xlim([-20, 20])
    plt.ylim([-20, 20])

示例输出:

constrained_random_walk(2000)


编辑:已更新,因此所有跳过的值都不是 (0,0),但 locations 中的每个值都由生成的移动填充。除了第一个,它被指定为起点。 (当前 (0,0))