Ising Model

A Monte Carlo simulation of the two-dimensional Ising model using the Metropolis algorithm

Written by Dan Schroeder, January 2003.  Modified for Mathematica 6 and later, January 2013.

Preliminaries:  Set the size of the lattice, initialize the lattice to a random array, define a function to plot the array in pretty colors, and plot the initial array:

size=50;
Clear[s];
s=Table[If[RandomInteger[]==0,1,-1],{i,1,size},{j,1,size}];
plotit:=ListDensityPlot[s,Mesh->False,InterpolationOrder->0,PlotRange->{-1,1},ColorFunction->(RGBColor[1-#,1-#,#]&)];
plotit

Next, define a function to compute the change in energy caused by a hypothetical flip of the dipole at location (i,j), using periodic boundary conditions:

deltaU[i_,j_]:=2*s[[i,j]]*(If[i==1,s[[size,j]],s[[i-1,j]]]+If[i==size,s[[1,j]],s[[i+1,j]]]+If[j==1,s[[i,size]],s[[i,j-1]]]+If[j==size,s[[i,1]],s[[i,j+1]]])

The following function executes the Metropolis algorithm at the specified temperature for any desired number of steps, then plots the array to show the results:

runawhile[T_,stepcount_]:=(For[step=0,step<stepcount,step++,i=RandomInteger[{1,size}];
j=RandomInteger[{1,size}];
Ediff=deltaU[i,j];
If[Ediff≤0,s[[i,j]]=-s[[i,j]],If[RandomReal[]<Exp[-Ediff/T],s[[i,j]]=-s[[i,j]]]]];
plotit)

For example, this invocation executes 100 steps per lattice site, at the critical temperature:

runawhile[2.27,100*size^2]

The following instruction produces an animated sequence of plots, with one step per lattice site between successive plots:

ListAnimate[Table[runawhile[2.27,size^2],{plotnum, 1, 50}]]