# -*- coding: utf-8 -*- from tkinter import * from random import choice # http://docs.python.org/library/random.html import numpy as np import matplotlib.pyplot as plt # http://matplotlib.sourceforge.net/api/pyplot_api.html#module-matplotlib.pyplot import matplotlib.mlab as mlab # http://matplotlib.sourceforge.net/api/mlab_api.html#module-matplotlib.mlab window = Tk() sizex = 400 sizey = 400 canvas = Canvas(window, width = sizex, height = sizey) canvas.pack() x = 200 # initial left-most edge of first ball y = 1 # initial top-most edge of first ball r = 4 # ball diameter depx = 1 # displacement at each move in x direction depy = 0 # create balls: no_particles = 1000 dy = (sizey-2.)/(no_particles+1) # y initial separation between balls #print dy ball_list=[] for i in range(no_particles): ball = canvas.create_oval(x,y,x+r,y+r,fill="blue") y = y+dy ball_list.append(ball) #moves no_moves = 400 for j in range(no_moves): for ball in ball_list: canvas.move(ball, choice([-1,-1,-1,-1,1,1,1,1,1,1])*depx, depy) #drift canvas.after(1) canvas.update() #analysis - histogram # see http://matplotlib.sourceforge.net/examples/api/histogram_demo.html xpos = [] for ball in ball_list: posi = canvas.coords(ball) xpos.append(posi[0]-x) xh = np.array(xpos) # see http://www.scipy.org/Cookbook/BuildingArrays # compute the mean mu and sigma from xh (and/or theoretical value from random walk result) mu = np.mean(xh) sigma = np.std(xh) fig = plt.figure() ax = fig.add_subplot(111) # print xh n, bins, patches = ax.hist(xh, 20, facecolor='green', alpha=0.75) print(mu, sigma) print(n,bins, patches) # hist uses np.histogram to create 'n' and 'bins'. # np.histogram returns the bin edges, so there will be ii probability # density values in n, ii+1 bin edges in bins and ii patches. To get # everything lined up, we'll compute the bin centers bincenters = 0.5*(bins[1:]+bins[:-1]) # add a 'best fit' line for the normal PDF yh = (bins[1]-bins[0])*no_particles*mlab.normpdf( bincenters, mu, sigma) # http://matplotlib.sourceforge.net/api/mlab_api.html#matplotlib.mlab.normpdf l = ax.plot(bincenters, yh, 'r--', linewidth=1) #print n ax.set_xlabel('X positions') ax.set_ylabel('Occurences') ax.grid(True) plt.show() #window.mainloop()