#!/usr/bin/env python # Simple python examples # python/centrallimit/randomwalk4w.py # David MacKay # # Make a walk with a fair coin, printing to file # the points reached at times 0, period, # 2*period, 3*period... # # Usage: # $ randomwalk4w.py [R [T [period [filename]]]] # Optional arguments: # R = number of walks # T = duration of walk # period = period between plots # # Example: # $ randomwalk4w.py 1 100 1 1walk.txt # $ randomwalk4w.py 8 10>000 10 8walks.txt import random import sys import os def walk(T, period, outputfile): """random walk with a fair coin""" x=0; outputfile.write( "0 \t"+str(x)+"\n" ) # start for t in xrange(T+1): u = random.random() if (u<= 0.5): x+=1 else: x-=1 if (t%period == 0 ) : outputfile.write( "%d \t %d\n" % ( t+1 , x ) ) pass def makewalks(R=10, T=100,period=1, filename="tmp.txt"): outputfile = open( filename , "w" ) for r in xrange(R): walk(T,period, outputfile) outputfile.write("\n\n") ## two blank lines ## between runs - useful for gnuplot outputfile.close(); if __name__ == '__main__': R=2 T=100 period=1 filename="tmp.txt" 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]) if(len(sys.argv)>4): filename=str(sys.argv[4]) makewalks(R, T, period , filename ) pass # This program illustrates # - how to read the command line # - how to print stuff to file ready for plotting # - 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