Study of 3 dimensional Ising model using Monte Carlo, Metropolis-Hastings Algorithm

29
Study of the 3 dimensional Ising model using Monte Carlo, Metropolis algorithm Indian Institute of Science Education and Research, Pune Devanshu Sinha working under supervision of Prof. Apratim Chatterji September 12, 2015

Transcript of Study of 3 dimensional Ising model using Monte Carlo, Metropolis-Hastings Algorithm

Study of the 3 dimensional Ising model usingMonte Carlo, Metropolis algorithm

Indian Institute of Science Education and Research, Pune

Devanshu Sinhaworking under supervision of Prof. Apratim Chatterji

September 12, 2015

AbstractIn this project, I use Monte Carlo technique, particularly the Metropolis algo-rithm, to computationally realise the 3 dimensional Ising model, and use it tostudy various properties of the lattice, for example, the variation of its heatcapacity with temperature, as it cools, or to see how average magnetisationvaries with time as we reach equilibrium, etc. An interesting property of thelattice, which is otherwise not realisable in real world experiments, namely,the finite size limit, will also be studied.

Introduction

With the ever increasing power andcapabilities of the computers, thefield of computational physics is be-coming extremely important in mod-ern times. Paraphrasing StephenWolfram, 1, a modern day scientistuses computers just like Galileo onceused his telescope, to look at theheavens and have a deeper under-standing of the workings of nature.Statistical mechanics is one particu-lar field which has greatly benefitedfrom computers, for it is a field ofextracting a bigger picture from thefine grainy details of a complex sys-tem. As quoted by Dr. LeonardSusskind 2 ’Statistical mechanics isperhaps the deepest fields of studyin physics, perhaps even more thanquantum mechanics’. I do not wish

to go into the argument about whichfield is deeper, but his words to re-veal the importance of statistical me-chanics, as well as the importance ofstudying it in greater detail. Moderncomputers have given yet another di-rection to study this vast field, andwith this small project I wish to give abrief glimpse to the reader, on how wego about implementing techniques tostudy systems from a statistical me-chanics point of view.Modern Monte Carlo technique waspioneered by Stanislaw Ulam and fur-ther developed by various other sci-entists, particularly John Von Nue-mann and others. The techniqueis based on iterative random sam-pling of a system to obtain numeri-cal results. I will use Monte Carlotechnique, to realise the Ising model,which models interacting system of

1Stephen Wolfram is the founder of Mathematica, one of the leading symbolic computerlanguages

2Prof. Susskind is a theoretical physicist at university of Stanford, he pioneered thestudy of Holographic principle and string theory.

1

atoms inside a lattice, and gives usthe net hamiltonian of the lattice,by summing over the hamiltonians ofeach of the lattice sites. The interac-tions in Ising model is only assumedupto the nearest neighbour, whichmakes it a rather crude, but never-theless useful model, to understandvarious properties of the system. If Si

and Sj are spins of the nearest neigh-bours for a lattice site, then the Isingmodel describes the Hamiltonian tobe

H = −J∑ij

SiSj (1)

If Sx,y,x is the spin at the lattice co-ordinates (x, y, z), then assuming weare working in a cubic lattice, theHamiltonian for that particular lat-tice site is thus written as

H = −J × (Sx,y,zSx+1,y,z +Sx,y,zSx−1,y,z + Sx,y,zSx,y−1,z

Sx,y,zSx,y+1,z + Sx,y,zSx,y,z−1 +Sx,y,zSx, y, z + 1)

It is worth highlighting at this pointthat in a 3D arrangement of a cu-bic lattice, for a given lattice site wehave 6 nearest neighbours, two aboveand below, two to the left and righteach and two in the front and back.We will let the axis passing throughthe front and back atoms to be x axis,the left and right axis to be the y axiswhile the up and down axis to be thez axis, thus working in standard righthanded coordinate system. For the

sake of simplicity, the lattice param-eter is taken to be unity, thus a +1translation from a given lattice sitein any direction parallel to any of thethree axis takes us to the next latticesite. Furthermore, although we aredealing with a cubic lattice, we willassume cyclic boundary conditions tokeep things simpler. Hence if we havean n×n×n lattice, and if we are on alattice site (n, y, z), then a +1 trans-lation in x direction would give us(1, y, z). This is easier to imagine in2 dimensions, for we can imagine the2D lattice being folded as a surfaceof a cylinder, connecting its two ends, which exists in +1 higher dimen-sion. 3D cyclic boundary conditions,although seem non-trivial, are nev-ertheless easily implementable in ouralgorithm.Once we implement the cyclic bound-ary conditions, we use FORTRAN’srandom number generator to ran-domise the spins of our n × n × nlattice. We then compute the netHamiltonian of the lattice using theIsing model by summing up the in-dividual Hamiltonians of each latticesite. We also compute the averagemagnetization of the lattice, whichis simply proportional to the sumof all the spins in our lattice. Thisaverage magnetization should be asmall number, if our n is big enough,for we have randomized each latticesite with either a +1 or a −1 spin,and thus one expects the net sum of

2

randomly arranged +1 or −1 to bearound 0. The exact form of averagemagnetization per spin is

Mav =

∑n3

i Si

n3(2)

The total energy is given by half ofthe initial sum, since we summed upeach of the lattice site twice whilegoing through the loop. The averageenergy per spin is then given by totalenergy divided by n3. The reason forcalculating these two values in ad-vance is because it reduces the com-putation. When we run our MonteCarlo trials, all we need to do is cor-rect the change in the energy andmagnetisation, instead going throughyet another loop.

Methodology

After initialising the lattice, we startour first loop which will store thevalue of the temperature, scaled insuch a way that our Boltzmann’s con-stant kB is unity. We start with theT = 5.5 and go down to T = 3.0 indecrements of 0.05. For each of thevalues of the temperature, we mustrun a large number of Monte Carlotrials in order to bring the lattice to

equilibrium. The number of trials inthis case, due to the my limited com-puting power, is chosen to be 20,000.This number can obviously be in-creased, depending upon the comput-ing power one has. I have selected a20×20×20 lattice for computing heatcapacity and magnetic susceptibilityversus temperature curves. I will usea smaller lattice size, 15×15×15 andfew other sizes, to see the time3 ver-sus instantaneous magnetisation4 andenergy curves, as the lattice reachesequilibrium for a given temperature.Inside our temperature loop, for ev-ery given temperature we will thusrun 20, 000 Monte Carlo trials. Foreach trial, we will need to implementthe Metropolis technique.

Metropolis Technique

Now that we are inside our MonteCarlo loop, we will need three moreloops, one in x, one in y and one inz, to sweep through the entire lattice.For every lattice site, we will need tocalculate the Hamiltonian, as we havealready seen, but now what we mustdo is, for the same lattice site, weflip the spin and compute its Hamil-tonian again. If this newly computedflipped spin Hamiltonian is less thanthe original Hamiltonian, we accept

3Time here is taken as the Monte Carlo trials themselves.4By instantaneous magnetisation, I mean the magnetisation of a microstate. This

should not be confused with the actual average magnetisation, which is an average of allthe microstates the system explores after reaching equilibrium

3

the move, and move on to the nextlattice site. However, if our flippedspin Hamiltonian is more than theoriginal Hamiltonian, there is still achance for the lattice to flip that spin.This probability is given by the Boltz-mann’s distribution. The fact thatthere is some chance for lattice in-creasing its energy, may be counter-intuitive, but if we think about it,what we are doing here is incorporat-ing thermal fluctuations in our model.A lattice in the real world does notimmediately come to the temperatureits kept in, but it slowly reaches thetemperature, while struggling withits internal thermal fluctuations. TheBoltzmann’s probability is given by

P (∆E) = e−

(Hafter−Hinitial)

kBT (3)

We repeat this procedure for everylattice site and complete our firstsweep. Every single such sweep gen-erates a possible microstate. Whileinside our sweeping loop, we alsokeep correcting our initial energy andmagnetisation for the completely ran-domised spin configuration. After wefinish our 20,000 Monte Carlo tri-als, we store the average and av-erage squared values of energy andmagnetisation for that given value oftemperature, and continue on witha lower temperature, repeating thesame steps.

Extra steps to Equilibratethe lattice

By experience we know that when thelattice attempts to reach a given tem-perature, there are allot of thermalfluctuations it has to battle, before itstarts to explore the states around thegiven temperature. The initial fewMonte Carlo trails have been spentto bring the lattice to equilibriumwith the given temperature and it isonly after this initial number of trialsthat we start correcting our originallycomputed energy and magnetisationvalues, for if we start correcting thevalues immediately, our initial datawill be lost due to large fluctuationsof energy and magnetisation. In thiscase, I have taken 2000 Monte Carlotrials, to first bring the lattice to equi-librium, and it is only after these ini-tial 2000 trials that I have started cor-recting my original data. The initialthermal fluctuations can be seen inthe following plot, here I have plottedthe energy versus time data for first300 Monte Carlo steps out of 20,000

4

We see the same behaviour in theinitial instantaneous magnetisation ofthe lattice as seen in the followingplot

It is apparent from the above plotsthat it is unwise to start correct-ing our initial energy and magnetisa-tion values immediately after the firstMonte Carlo step, and it should alsobe apparent from the same plot, that

both plots, even after only a few tri-als, do start settling down to someaverage value around which they fluc-tuate for the rest of the Monte Carlosteps. If we look at the same twoplots where the x axis is scaled up toinclude all 20,000 steps, we see thatthe initial fluctuations do not inter-fere with the rest of the steps, and wedo not get large fluctuations after theinitial equilibrium steps, thus justify-ing our initial assumption.

The instantaneous magnetisation alsosettles around an average value neareither positive 1 5 or -1.

5Not exactly 1, it is always less than 1 or -1

5

Results for Heat Ca-

pacity and Magnetic

susceptibility

The heat capacity Cv is given by

Cv =< E2 > − < E >2

kBT 2(4)

For our 20 × 20 × 20 lattice, we getthe following results for temperatureversus heat capacity curve.

Here the temperature has been scaledin such a way that the units of kB isset to 1. This simplifies the calcula-tion and does not disturb the overallstructure of the curve. The values of< E >2 and < E2 > have been ob-tained from the trails, for each T . Icooled the lattice down from T = 5to T = 3 as my supervisor had givenme some idea of where the transitionshould occur. The cooling was donein steps of 0.05. From the data itself,we can see that the phase transitionin our present case happens to be at

around Tc = 4.5.The magnetic susceptibility, which isgiven by

χ =< M2 > − < M >2

kBT(5)

Gives the following results, for thesame lattice size and same number oftrials.

Again, the the phase transition tem-perature is about the same in bothcases.

Average Energy and

average magnetisation

versus Temperature

The average energy versus tempera-ture data gives us the following result.

6

In this case, I have cooled down thelattice further than T = 3.0. Thereason was to be able to get a bet-ter sense of the behaviour. We canobserve that as the lattice cools theenergy decreases slowly with tem-perature, but starts dropping ratherquickly as we reach the critical tem-perature. The average magnetisationversus temperature gives us the fol-lowing result

Again we can observe that as we coolthe lattice, the average magnetisationfluctuates around zero but the latticesuddenly starts getting magnetised aswe reach the critical temperature Tc.

Smaller lattice sizes -

Finite size problem

In our model so far, we have been ex-ploring the properties of a 20×20×20size lattice, which is small enoughthat it is computable on a nor-mal home computer, but also largeenough to be able to reproduce datawhose behaviour does match roughlywith the experiments. However, it isapparent that in real world we do nothave a lattice which only has 8000atoms. We generally deal with thelattice sizes of the order of a molecubed. The goal of this section willbe to further decrease the sze of ourlattice, and see if the behaviour of ourdata deviates from the experimentalresults, and if so, then what could bethe reason. We will be trying to seethe time versus magnetisation plotsfor smaller lattice sizes and see if thelattice jumps to either a positive or anegative value of magnetisation. Fol-lowing are the results

For lattice size of 20

7

For lattice size of 7

For lattice size of 4

We observe that as we decrease ourlattice size, the system does notjump on to either positive or a nega-tive magnetisation, but rather keepsjumping back and forth from positiveto negative. In a very small lattice,which is only 4 atoms thick, the aver-age magnetisation is zero, as we cansee in the plot above. The reasonthat this happens for a small latticeis because of the smaller energy bar-rier the atoms have to cross in orderto flip their spins. For a large latticethis does not happen because once acertain number of spins start aligning

in one particular direction, the sys-tem generates its own field and be-comes biased towards that direction,and soon enough the entire configura-tion aligns itself in that direction andexplores the microstates around someaverage negative or positive value.The energy barrier that atoms haveto cross, to struggle against the largeinternal field and flip their spins isvery large in lattices with large num-ber of atoms. From the above plotswe can also see why macroscopic val-ues do tell us a good deal about thesystem. We can see this if we lookat the spread of the data points visu-ally in the plots. As we increase thesize of the lattice, the points becomemore tightly packed together aroundsome average value. Now if we cansee this tight packing only in a lattice20 atoms wide, we can imagine howcertain the average magnetisation be-comes if we increase the lattice sizesuch that it is an order of 1023 some-thing atoms wide.

Behaviour under influ-

ence of external mag-

netic field

In this section we explore the be-haviour under the influence of ex-ternal magnetic field. Intuitively wecan imagine that if we initially biasthe lattice with an external mag-

8

netic field, it will always settle toa net magnetised configuration withnet spin aligned in the direction of theexternal field. I will incorporate thisexternal magnetic field in our modelby modifying the earlier Hamiltonianin the following way

H = −J∑i,j

SiSj −B∑i

Si (6)

For the lattice size of 20× 20× 20 wewill try to see what happens to heatcapacity, magnetic susceptibility etc.

Results for heat capacityand magnetic susceptibil-ity versus temperature un-der external field of B = 0.1

Following were the results obtainedupon plotting the heat capacity ver-sus temperature data under an exter-nal field of 0.1

As we can see that the critical tem-perature still remains the same. Thisresult is supported further when weplot the magnetic susceptibility ver-sus temperature data, as shown be-low

The lattice suddenly starts get-ting magnetised upon cooling it, atthe same critical temperature, even

6That is, assuming we have a large number of atoms and are beyond the errors comingdue to the finite size limit

9

though we have been influencing itwith a high external magnetic field.Thus we have shown an example ofthe fact that the critical temperatureis an intrinsic property of the lattice6.

Results for average energyand average magnetisationversus temperature underexternal field of B=0.1

Following is the energy versus tem-perature curve we get under an ex-ternal field

The results are the same as our pre-vious data, with the energy slightlyhigher, but the structure being thesame. The average energy this timehas been scaled to the size of our lat-tice, thus I have actually plotted E

L3

versus T . For the average magneti-sation we get following results (againscaled to the lattice size)

Here we can see that the aver-age magnetisation versus tempera-ture behaviour to be the same underthe influence of external field as with-out it.

Results for smaller lat-

tice sizes

Now that we have looked at the re-sults for a standard lattice, which islarge enough to get a good approx-imation to actual experimental re-sults, I will reduce the size of the lat-tice and show the average magneti-sation, average energy, heat capac-ity and magnetic susceptibility versustemperature data in this section.

10

For a 15x15x15 lattice

Heat Capacity versus temperaturecurve

Magnetic susceptibility versustemperature curve

Average energy versus temperature

Average magnetisation versustemperature

Here we can see that the criticaltemperature has decreased a little bitupon decreasing the size of our lat-tice. Following is the data for an evensmaller lattice size

11

For a 10x10x10 lattice

Heat Capacity versus temperaturecurve

Magnetic susceptibility versustemperature curve

Average energy versus temperature

Average magnetisation versustemperature

12

For a 15x15x15 lattice

Heat Capacity versus temperaturecurve

Magnetic susceptibility versustemperature curve

Average energy versus temperature

Average magnetisation versustemperature

Here we can see that the criticaltemperature has decreased a little bitupon decreasing the size of our lat-tice. Following is the data for an evensmaller lattice size

13

For a 5x5x5 lattice

Heat Capacity versus temperaturecurve

Magnetic susceptibility versustemperature curve

Average energy versus temperature

Average magnetisation versustemperature

The effect of small size of the lattice,which was explored in a previous sec-tion, is apparent in the average mag-netisation versus temperature curve.The energy barrier that the atomsmust cross to reverse the directionof their spins becomes smaller dueto the smaller size of the lattice, be-cause they have to struggle against a

14

lower value of the internal field. Thisresults in the fluctuation of averagemagnetisation, from positive to thenegative sides below the critical tem-perature. We can also see that foreven such small lattice size, the crit-ical temperature does not vary muchfrom the earlier 4.5, but as a generaltrend we do see a decrease in criti-cal temperature if we start going be-low a small enough size. For real lifelattices with much larger number ofatoms, this variation of critical tem-perature is not observed, and it doesindeed remain an intrinsic property ofthe material.

Results for 2D Ising

model

Out of curiosity, I reduced the di-mensions of my 3D Ising model codeto 2D, and found much better look-ing curves for energy, magnetisation,heat capacity and so forth. Followingwere the results

Heat Capacity versus temperaturecurve

Magnetic susceptibility versustemperature curve

15

Average energy versus temperature

Average magnetisation versustemperature

So we can see that the criticaltemperature drops from about 4.5 to2.3 upon reducing the dimensions ofthe lattice. Does this trend continuefor lower and higher dimension? Iknow for sure that it does indeed dropfurther when we consider a 1D Isingmodel, but according to what I have

found out from wikipedia, we can-not work with Ising model any fur-ther than three dimensions, and wemust consider other models for study-ing the behaviour of the lattice forhigher dimensions.

16

References

1. Prof.Apratim Chatterji’s lecturenotes on statistical mechanics andprogramming2. Wikipedia.org

3. Concepts of thermal physics -Stephen Blundell4. Binder K., Heermann D.W.Monte Carlo Simulation in StatisticalPhysics 2010

17

Conclusion

In this project we learnt how to implement an existing physical model into acomputational one, by techniques such as Monte Carlo. We found out howcomputers can tell us new things about nature, which cannot be intuitivelyapparent or even analytically solvable. I would like to thank my projectsupervisor Prof. Apratim Chatterji from whom I learnt lots of fun thingsabout computational physics which will help me in my future work, and myseniors, Tejal and Mainak for helping me with the model.

Code for Ising model with no external field

program isingmodelfinal

implicit none

real:: E, M, T,r, avg_en, avg_sq_en, avg_mag, avg_sq_mag, mag_sus, sums, dE, rnd

real,dimension(4)::cum

real:: heat_capacity

integer, parameter :: J = -1

integer, parameter :: L = 20

integer, parameter :: totstep = 20000

integer, parameter :: equil = 2000

integer :: x,y,z, up, right, accept, N,i,k, left, down,w, front, back

integer,dimension(L,L,L):: spin

accept=0

N = L*L*L

call random_seed()

E = 0.0

M = 0.0

cum(1) = 0.0

cum(2) = 0.0

cum(3) = 0.0

cum(4) = 0.0

do x=1,L

18

do y=1,L

do z=1,L

call random_number(r)

if(r .lt. 0.5) then

Spin(x,y,z) = -1

else

Spin(x,y,z) = +1

end if

M = M + Spin(x,y,z)

end do

end do

end do

do x=1,L

do y=1,L

do z=1,L

!impose cyclic boundary conditions and give values to variables

up = y + 1

right = x + 1

front = z + 1

!cyclic conditions

if(x.eq.L) right = 1

if(y .eq. L) up = 1

if(z .eq. L) front = 1

sums = Spin(x,up,z) + Spin(right,y,z) + Spin(x,y,front)

E = E + J*Spin(x,y,z)*sums

end do

end do

end do

print*, E,’ ’, M

do T=6.0,3.5,-0.05

avg_en = 0.0

avg_sq_en = 0.0

19

avg_mag = 0.0

avg_sq_mag = 0.0

do i = 1,equil !bring system to equilibrium

do x = 1,L

do y = 1,L

do z = 1,L

if (x == 1) then

left = spin(L,y,z)

right = spin(2,y,z)

else if (x == L) then

left = spin(L-1,y,z)

right = spin(1,y,z)

else

left = spin(x-1,y,z)

right = spin(x+1,y,z)

end if

if (y == 1) then

up = spin(x,2,z)

down = spin(x,L,z)

else if (y == L) then

up = spin(x,1,z)

down = spin(x,L-1,z)

else

up = spin(x,y+1,z)

down = spin(x,y-1,z)

end if

if (z == 1) then

back = spin(x,y,L)

front = spin(x,y,2)

else if (z == L) then

back = spin(x,y,L-1)

front = spin(x,y,1)

else

back = spin(x,y,z-1)

front = spin(x,y,z+1)

20

end if

dE = 2*spin(x,y,z)*(left + right + up + down + front + back)

call random_number(rnd)

if (rnd .lt. exp(-dE/T)) then

spin(x,y,z) = -spin(x,y,z)

accept = accept + 1

M = M + 2*spin(x,y,z)

E = E + dE

end if

end do !for z

end do !for y

end do !for x

end do !for equil

do k = 1,totstep

do x = 1,L

do y = 1,L

do z = 1,L

if (x == 1) then

left = spin(L,y,z)

right = spin(2,y,z)

else if (x == L) then

left = spin(L-1,y,z)

right = spin(1,y,z)

else

left = spin(x-1,y,z)

right = spin(x+1,y,z)

end if

if (y == 1) then

up = spin(x,2,z)

down = spin(x,L,z)

else if (y == L) then

up = spin(x,1,z)

down = spin(x,L-1,z)

else

up = spin(x,y+1,z)

21

down = spin(x,y-1,z)

end if

if (z == 1) then

back = spin(x,y,L)

front = spin(x,y,2)

else if (z == L) then

back = spin(x,y,L-1)

front = spin(x,y,1)

else

back = spin(x,y,z-1)

front = spin(x,y,z+1)

end if

dE = 2*spin(x,y,z)*(left + right + up + down + front + back)

call random_number(rnd)

if (rnd .lt. exp(-dE/T)) then

spin(x,y,z) = -spin(x,y,z)

accept = accept + 1

M = M + 2*spin(x,y,z)

E = E + dE

end if

end do !for z

end do !for y

end do !for x

cum(1) = cum(1) + E

cum(2) = cum(2) + E*E

cum(3) = cum(3) + M

cum(4) = cum(4) + M*M

end do

avg_en = cum(1)/totstep

avg_sq_en = cum(2)/totstep

avg_mag = cum(3)/totstep

avg_sq_mag = cum(4)/totstep

heat_capacity = (avg_sq_en - avg_en*avg_en)/(T*T)

mag_sus = (avg_sq_mag - avg_mag*avg_mag)/T

print*, T,’ ’, avg_en/n,’ ’,avg_sq_en/n,’ ’,avg_mag/n,’ ’,avg_sq_mag/n,’ ’,heat_capacity/n,’ ’,mag_sus/n

open(unit=1,file=’latticesize20.dat’)

22

write(1,*) T,’ ’,avg_en/n,’ ’,avg_mag/n,’ ’,heat_capacity/n,’ ’,mag_sus/n

do w=1,4

cum(w)=0.0

end do

end do !for T

close(unit=1)

end program isingmodelfinal

23

Ising model with an external field parameter

B

program externalfield

implicit none

real:: E, M, T,r, avg_en, avg_sq_en, avg_mag, avg_sq_mag, mag_sus, sums, dE, rnd

real,dimension(4)::cum

real:: heat_capacity

integer, parameter :: J = -1

integer, parameter :: L = 20

integer, parameter :: totstep = 20000

integer, parameter :: equil = 2000

integer, parameter :: B = 0.1

integer :: x,y,z, up, right, N,i,k, left, down,w, front, back

integer,dimension(L,L,L):: spin

N = L*L*L

call random_seed()

E = 0.0

M = 0.0

cum(1) = 0.0

cum(2) = 0.0

cum(3) = 0.0

cum(4) = 0.0

do x=1,L

do y=1,L

do z=1,L

call random_number(r)

if(r .lt. 0.5) then

Spin(x,y,z) = -1

else

24

Spin(x,y,z) = +1

end if

M = M + Spin(x,y,z)

end do

end do

end do

do x=1,L

do y=1,L

do z=1,L

!impose cyclic boundary conditions and give values to variables

up = y + 1

right = x + 1

front = z + 1

!cyclic conditions

if(x.eq.L) right = 1

if(y .eq. L) up = 1

if(z .eq. L) front = 1

sums = Spin(x,up,z) + Spin(right,y,z) + Spin(x,y,front)

E = E + J*Spin(x,y,z)*(sums + B)

end do

end do

end do

print*, E,’ ’, M

do T=6.0,3.5,-0.05

avg_en = 0.0

avg_sq_en = 0.0

avg_mag = 0.0

avg_sq_mag = 0.0

do i = 1,equil !bring system to equilibrium

do x = 1,L

do y = 1,L

25

do z = 1,L

if (x == 1) then

left = spin(L,y,z)

right = spin(2,y,z)

else if (x == L) then

left = spin(L-1,y,z)

right = spin(1,y,z)

else

left = spin(x-1,y,z)

right = spin(x+1,y,z)

end if

if (y == 1) then

up = spin(x,2,z)

down = spin(x,L,z)

else if (y == L) then

up = spin(x,1,z)

down = spin(x,L-1,z)

else

up = spin(x,y+1,z)

down = spin(x,y-1,z)

end if

if (z == 1) then

back = spin(x,y,L)

front = spin(x,y,2)

else if (z == L) then

back = spin(x,y,L-1)

front = spin(x,y,1)

else

back = spin(x,y,z-1)

front = spin(x,y,z+1)

end if

dE = 2*spin(x,y,z)*(left + right + up + down + front + back + B)

call random_number(rnd)

if (rnd .lt. exp(-dE/T)) then

spin(x,y,z) = -spin(x,y,z)

26

M = M + 2*spin(x,y,z)

E = E + dE

end if

end do !for z

end do !for y

end do !for x

end do !for equil

do k = 1,totstep

do x = 1,L

do y = 1,L

do z = 1,L

if (x == 1) then

left = spin(L,y,z)

right = spin(2,y,z)

else if (x == L) then

left = spin(L-1,y,z)

right = spin(1,y,z)

else

left = spin(x-1,y,z)

right = spin(x+1,y,z)

end if

if (y == 1) then

up = spin(x,2,z)

down = spin(x,L,z)

else if (y == L) then

up = spin(x,1,z)

down = spin(x,L-1,z)

else

up = spin(x,y+1,z)

down = spin(x,y-1,z)

end if

if (z == 1) then

back = spin(x,y,L)

front = spin(x,y,2)

else if (z == L) then

27

back = spin(x,y,L-1)

front = spin(x,y,1)

else

back = spin(x,y,z-1)

front = spin(x,y,z+1)

end if

dE = 2*spin(x,y,z)*(left + right + up + down + front + back + B)

call random_number(rnd)

if (rnd .lt. exp(-dE/T)) then

spin(x,y,z) = -spin(x,y,z)

M = M + 2*spin(x,y,z)

E = E + dE

end if

end do !for z

end do !for y

end do !for x

cum(1) = cum(1) + E

cum(2) = cum(2) + E*E

cum(3) = cum(3) + M

cum(4) = cum(4) + M*M

end do

avg_en = cum(1)/totstep

avg_sq_en = cum(2)/totstep

avg_mag = cum(3)/totstep

avg_sq_mag = cum(4)/totstep

heat_capacity = (avg_sq_en - avg_en*avg_en)/(T*T)

mag_sus = (avg_sq_mag - avg_mag*avg_mag)/T

print*, T,’ ’, avg_en/N,’ ’,avg_sq_en/N,’ ’,avg_mag/N,’ ’,avg_sq_mag/n,’ ’,heat_capacity/n,’ ’,mag_sus/n

open(unit=1,file=’externalfield01.dat’)

write(1,*) T,’ ’,avg_en/n,’ ’,avg_mag/n,’ ’,heat_capacity/n,’ ’,mag_sus/n

do w=1,4

cum(w)=0.0

end do

end do !for T

close(unit=1)

end program externalfield

28