Posted By

bingjian on 08/03/09


Tagged

random simulation RandomWalk BrownianMotion


Versions (?)

Random Walks


 / Published in: Python
 

  1. import numpy
  2. import random
  3. import copy
  4. from pyx import *
  5.  
  6. class RandomWalker:
  7.  
  8. def __init__(self, dim = 2, max_step = 100):
  9. self.dim = dim
  10. self.origin = numpy.zeros(dim)
  11. self.max_step = max_step
  12. self.trajectory = [self.origin]
  13. self.position = copy.copy(self.origin)
  14. self.time = 0
  15. pass
  16.  
  17. def walk(self, step=1):
  18. for k in range(step):
  19. self.time += 1
  20. direction = random.randint(0,self.dim-1)
  21. self.position[direction] += [-1,1][random.randint(0,1)]
  22. self.trajectory.append(copy.copy(self.position))
  23.  
  24. def clear(self):
  25. self.__init__(self.dim)
  26.  
  27.  
  28. def plot(self, filename):
  29. c = canvas.canvas()
  30. x_min = min([i[0] for i in self.trajectory])
  31. x_max = max([i[0] for i in self.trajectory])
  32. y_min = min([i[1] for i in self.trajectory])
  33. y_max = max([i[1] for i in self.trajectory])
  34.  
  35. p = path.path(path.moveto(self.origin[0]-x_min,self.origin[1]-y_min))
  36. for i in range(self.time-1):
  37. x,y = self.trajectory[i+1]
  38. p.append(path.lineto(x-x_min,y-y_min))
  39. c.stroke(p)
  40. c.writeEPSfile(filename)
  41. c.writePDFfile(filename)

Report this snippet  

You need to login to post a comment.