【发布时间】:2017-04-21 09:19:43
【问题描述】:
我有一个 for 循环,它在第一次迭代后返回零。我让它打印出 i,所以我知道它实际上是在循环,但由于某种原因,它似乎没有在第一次迭代后调用我的函数 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])
print 应该打印出函数返回的列表之一,但除了第一次迭代之外,列表的所有元素都为零。如果我用 N=any 值在循环外调用函数,那么元素不为零,所以问题似乎是循环。我有另一个具有完全相同循环的 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 个列表包含非零元素。
【问题讨论】:
-
我们没有您的
new_lattice功能,因此这不是一个可验证的完整示例。请提供足够的代码来重现您的错误。 -
而且预期的输出也会很好
-
您可以在
new_lattice中添加一个print调用,看看它是否真的进入了那里。 -
问题一定出在你的
init_lattice或new_lattice -
它说'bootstraps'没有定义
标签: python python-3.x loops for-loop