我有一个for循环,在第一次迭代后返回零 . 我把它打印出来,所以我知道它实际上已经循环,但由于某种原因它似乎并没有在第一次迭代后调用我的函数new_lattice .
N=[4,8,16,20,25]
for i,j in enumerate(N):
print(i)
init_lattice=np.ones((j,j))
#new_lattice is a function that returns multiple lists
data=new_lattice(init_lattice,j)
print (data[1])
打印应打印出函数返回的一个列表,但除第一次迭代外,列表的所有元素都为零 . 如果我在循环外调用N =任意值的函数,那么元素不为零,所以它似乎是循环问题 . 我有另一个python文件具有完全相同的循环,但那个工作,所以我不明白为什么这不!
这是完整的代码,包括函数:
import numpy as np
from numpy import random as rn
import matplotlib.pyplot as plt
temp1= np.arange(2.0, 3.0, 0.1)
temp=enumerate(temp1)
number_of_sweeps=200
eqm_sweeps=50
def new_lattice(lattice,L):
delta_E=np.zeros((L,L))
mag=np.zeros(number_of_sweeps)
mag1=np.zeros(len(temp1))
mag2=np.zeros(len(temp1))
mag4=np.zeros(len(temp1))
for n, T in temp:
for sweep in range(number_of_sweeps+eqm_sweeps):
for i in range(L):
for j in range(L):
Si=lattice[i,j]
sum_Sj=lattice[i,(j+1)%L]+lattice[(i+1)%L,j]+lattice[i,(j-1)%L]+lattice[(i-1)%L,j]
delta_E[i,j]=2*Si*sum_Sj
if delta_E[i,j] > 0.0 and rn.random() < np.exp(-1*delta_E[i,j]/(T)):
lattice[i,j] *= -1
elif delta_E[i,j] <= 0.0:
lattice[i,j] *= -1
if sweep>=eqm_sweeps:
mag[sweep-eqm_sweeps]=abs(np.sum(lattice))
mag1[n]=np.sum(mag)/number_of_sweeps
mag2[n]=np.sum(mag**2)/((L**2)*number_of_sweeps)
mag4[n]=np.sum(mag**4)/((L**2)*number_of_sweeps)
return mag1, mag2,mag4,lattice
该代码使用Metropolis算法来模拟Ising模型 . 输出如下:
0
[ 3323.37 3225.43 2912.865 2740.01 2392.66 2266.455 1964.165
1804.22 1595.68 1317.135]
1
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
2
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
3
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
4
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
但我希望最后4个列表具有非零元素 .