我在python(2d)中有一些Ising模型的代码,格子不会达到平衡。这里,代码打印出每次蒙特卡罗扫描时翻转的旋转次数,并且每次扫描都会翻转相同的数字。如果我是正确的,那么当晶格达到平衡时,随着每次扫描,翻转的数量应该减少。任何人都可以看到代码中的任何错误吗?
import numpy as np
from numpy import random as rn
N=20
a=[1,-1]
b=[N,N]
#first make an array
init_lattice=rn.choice(a,size=(N,N))
#specify how many Monte Carlo sweeps
number_of_sweeps=1000
#main code to flip spins and record how many are flipped
def new_lattice(lattice,T):
delta_E=np.zeros(b)
switch1=np.zeros(number_of_sweeps)
switch=0
for sweep in range(number_of_sweeps):
for i in range(N):
for j in range(N):
Si=lattice[i,j]
sum_Sj=lattice[i,(j+1)%N]+lattice[(i+1)%N,j]+lattice[i,(j-1)%N]+lattice[(i-1)%N,j]
delta_E[i,j]=2*Si*sum_Sj
if delta_E[i,j]<0:
lattice[i,j]*=-1
switch+=1
elif np.exp(-1*delta_E[i,j]/(T))>rn.random():
lattice[i,j]*=-1
switch+=1
switch1[sweep]=switch
return lattice,switch1
#print how many spins have flipped
switch= new_lattice(init_lattice,5)[1]
print switch
for i in range(len(switch)):
print switch[i+1]-switch[i-1]
答案 0 :(得分:1)
我认为循环
for i in range(N):
for j in range(N):
不好:你必须选择你想要随机测试的旋转。
T和其他变量是整数,你将在指数np.exp(-1 * delta_E [i,j] / T)中有一个整数除法,这是错误的。
使用此代码我有饱和度(注意我取T = 1而不是5.而扫描= 10000而不是1000):
import numpy as np
from numpy import random as rn
import random
import matplotlib.pyplot as plt
latticeDimensions = [20, 20]
nx = latticeDimensions[0]
ny = latticeDimensions[1]
nodesNumber = nx*ny
spinValues = [-1,1]
sweeps = 10000
T = 1.
lattice = init_lattice = rn.choice(spinValues,size=(nx,ny))
#lattice = [ random.choice([-1,1]) for i in range(nodesNumber) ]
t = 0
switch = 0
res = []
while t < sweeps:
selectedNode = random.choice(nodeIdx)
i = random.choice(range(nx))
j = random.choice(range(ny))
Si = lattice[i,j]
sum_Sj=lattice[i,(j+1)%ny] + lattice[(i+1)%nx,j] + lattice[i,(j-1)%ny] + lattice[(i-1)%nx,j]
delta = 2 * Si * sum_Sj
probaTemp = np.exp(- delta / T)
if delta > 0. and rn.random() < probaTemp:
lattice[i,j] *= -1
switch += 1
elif delta <= 0.:
lattice[i,j] *= -1
switch += 1
t += 1
print t
res.append(switch)
plt.plot(res)
plt.show()