#!/usr/bin/env python
# Simple python examples
# python/centrallimit/randomwalk5.py
# David MacKay
#
# Make a walk with a fair coin, plotting
# with Gnuplot the points reached at times
# 0, period, 2*period, 3*period...
#
# Usage:
# $ randomwalk5.py [R [T [period]]]
# Optional arguments:
# R = number of walks
# T = duration of walk
# period = period between points shown
#
# Example: - make one walk
# $ randomwalk5.py 1 100 1
# - make 8 walks, and plot every 10th point
# $ randomwalk5.py 8 10000 10
import random
import sys
import Gnuplot, Gnuplot.funcutils
def walk(T=10, period=1):
"""random walk with a fair coin"""
x=0; answer= [[0,0]]
for t in xrange(T+1):
u = random.random()
if (u<= 0.5): x+=1
else: x-=1
if (t%period == 0 ) :
answer.append([ t+1 , x ])
return answer
def makewalks(R=10, T=100,period=1):
"""Makes walks and plots them with gnuplot"""
g = Gnuplot.Gnuplot(persist=1) #(debug=1, persist=1)
g.title('Random walks')
g('set data style line')
for r in xrange(R):
newwalk = walk(T,period)
if(r==0): g.plot(newwalk) ; pass
else: g.replot(newwalk) ; pass
if __name__ == '__main__':
R=2
T=100
period=1
if(len(sys.argv)>1):
R=int(sys.argv[1])
if(len(sys.argv)>2):
T=int(sys.argv[2])
if(len(sys.argv)>3):
period=int(sys.argv[3])
makewalks(R, T, period )
pass
# This program illustrates
# - how to read the command line
# - how to plot lists of lists in gnuplot
# - how to use random.random()
# (there are many other random functions
# available in python; random.random()
# makes numbers between 0 and 1)
# - how to write a package that contains
# functions and that has a default behaviour
# if run directly from a terminal
# or from a python development environment
|