2D random walk with walls; scalar version.
Modify the walk2D.py or walk2Dc.py programs from Exercise 8.35 so that the walkers cannot walk outside a rectangular area A = [xL, xH]× [yL, yH]. Do not move the particle if its new position is outside A. Name of program file: walk2D_barrier.py.
Exercise 8.35
Make a class for 2D random walk.
The purpose of this exercise is to reimplement the walk2D.py program from Chapter 8.7.1 with the aid of classes. Make a class Particle with the coordinates (x, y) and the time step number of a particle as attributes. A method move moves the particle in one of the four directions and updates the (x, y) coordinates. Another class, Particles, holds a list of Particle objects and a plotstep parameter (as in walk2D.py). A method move moves all the particles one step, a method plot can make a plot of all particles, while a method moves performes a loop over time steps and calls move and plot in each step.
Equip the Particle and Particles classes with print functionality such that one can print out all particles in a nice way by saying print p (for a Particles instance p) or print self (inside a method). Hint: In __str__, apply the pformat function from the pprint module to the list of particles, and make sure that __repr__ just reuse __str__ in both classes.
To verify the implementation, print the first three positions of four particles in the walk2D.py program and compare with the corresponding results produced by the class-based implementation (the seed of the random number generator must of course be fixed identically in the two programs). You can just perform p.move() and print p three times in a verify function to do this verification task.
Organize the complete code as a module such that the classes Particle and Particles can be reused in other programs. The test block should call a run(N) method to run the walk for N steps, where N is given on the command line.
Compare the efficiency of the class version against the vectorized version in walk2Dv.py, using the techniques of Appendix G.6.1. Name of program file: walk2Dc.py.