Random Walk

本文通过Python实现了一个简单的随机行走模拟程序。模拟中,醉汉(Drunk类)在一个二维平面上随机选择北、南、东、西四个方向之一,并每次移动一步。使用Location类来表示位置坐标,CompassPt类来表示方向,Field类来表示行走的场域。通过对行走距离随时间的变化进行绘图,直观展示了随机行走的特点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import math, random, pylab

#matplotlib-1.0.1.win32-py2.7.exe

#numpy-1.6.0b2-win32-superpack-python2.7.exe

 

class Location(object):
  def __init__(self, x, y):
    self.x = float(x)
    self.y = float(y)
  def move(self, xc, yc):
    return Location(self.x+float(xc), self.y+float(yc))
  def getCoords(self):
    return self.x, self.y
  def getDist(self, other):
    ox, oy = other.getCoords()
    xDist = self.x - ox
    yDist = self.y - oy
    return math.sqrt(xDist**2 + yDist**2)

 

class CompassPt(object):
  possibles = ('N', 'S', 'E', 'W')
  def __init__(self, pt):
    if pt in self.possibles: self.pt = pt
    else: raise ValueError("in CompassPt.__init__")
  def move(self, dist):
    if self.pt == 'N': return (0, dist)
    elif self.pt == 'S': return (0, -dist)
    elif self.pt == 'E': return (dist, 0)
    elif self.pt == 'W': return (-dist, 0)
    else: raise ValueError("in CompassPt.move")

 

class Field(object):
  def __init__(self, drunk, loc):
    self.drunk = drunk
    self.loc = loc
  def move(self, cp, dist):
    oldLoc = self.loc
    xc, yc = cp.move(dist)
    self.loc = oldLoc.move(xc, yc)
  def getLoc(self):
    return self.loc
  def getDrunk(self):
    return self.drunk

 

class Drunk(object):
  def __init__(self, name):
    self.name = name
  def move(self, field, time = 1):
    if field.getDrunk() != self:
      raise ValueError("Drunk.move called with drunk not in field")
    for i in range(time):
      pt = CompassPt(random.choice(CompassPt.possibles))
      field.move(pt, 1)

 

def performTrial(time, f):
  start = f.getLoc()
  distances = [0.0]
  for t in range(1, time + 1):
    f.getDrunk().move(f)
    newLoc = f.getLoc()
    distance = newLoc.getDist(start)
    distances.append(distance)
  return distances

 

#assert False

 

drunk = Drunk('Homer Simpson')
for i in range(3):
  f = Field(drunk, Location(0, 0))
  distances = performTrial(500, f)
  pylab.plot(distances)
pylab.title("Homer's Random Walk")
pylab.xlabel("Time")
pylab.ylabel("Distance from Origin")

pylab.show()
#assert False

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值