我不擅长编程,为了弄清楚这一点,我已经把自己逼疯了。你知道吗
我有一个计算结合能的程序,它把值存储在列表中。在某一点上,一个列表被另一个列表所除,但我不断得到这个错误:
Traceback (most recent call last):
File "semf.py", line 76, in <module>
BpN = BpN(A, Z)
File "semf.py", line 68, in BpN
bper = B[i]/A[i]
IndexError: list index out of range
相关代码如下,很抱歉太多了:
A = 0.0
def mass_A(Z):
"""
ranges through all A values Z, ..., 3Z+1 for Z ranging from 1 to 100
"""
a = 0.0
a = np.arange(Z, 3*Z+1)
return a
def semf(A, Z):
"""
The semi-empirical mass formula (SEMF) calculates the binding energy of the nucleus.
N is the number of neutrons.
"""
i = 0
E = []
for n in A:
# if statement to determine value of a5
if np.all(Z%2==0 and (A-Z)%2==0):
a5 = 12.0
elif np.all(Z%2!=0 and (A-Z)%2!=0):
a5 = -12.0
else:
a5 = 0
B = a1*A[i] - a2*A[i]**(2/3) - a3*(Z**2 / A[i]**(1/3)) - a4*( (A[i] - 2*Z)**2 / A[i] ) + a5 / A[i]**(1/2)
i += 1
E.append(B)
return E
def BpN(A, Z):
"""
function to calculate the binding energy per nucleon (B/A)
"""
i = 0
R = []
for n in range(1,101):
bper = B[i]/A[i]
i += 1
R.append(bper)
return R
for Z in range(1,101):
A = mass_A(Z)
B = semf(A, Z)
BpN = BpN(A, Z)
似乎不知何故,两个列表A和B的长度不一样,但我不知道如何解决这个问题。你知道吗
请帮忙。你知道吗
谢谢
在Python中,列表索引从零开始,而不是从一开始。你知道吗
如果不完整地查看代码,很难确定,但是
range(1,101)
看起来很可疑。如果列表有100个元素,那么循环的正确界限是range(0,100)
,或者,等价地,range(100)
,或者更好的是,range(len(A))
。你知道吗另外,既然您已经在使用Numpy了,那么您应该考虑使用Numpy数组重写代码,而不是使用列表和循环。如果
A
和B
是Numpy数组,那么整个麻烦函数可能会变成:(这是
B
除以A
的元素划分。)相关问题 更多 >
编程相关推荐