首页 > 解决方案 > 将数组中的最大值附加到另一个数组时索引错误

问题描述

我对此代码的输出有疑问:

from math import *
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
a1=15.8
a2=18.3
a3=0.714
a4=23.2

def bindingenergy():
    maxvalues=[]
    for Z in range (1,106):
        values=[]
        for A in range (Z, 3*Z+1):
            if A%2==1:
                a5=0
            elif A%2==0 and Z%2==0:
                a5=12
            else:
                a5=-12
            B=a1*A-a2*A**(2/3)-a3*((Z**2)/A**(1/3))-a4*(((A-2*Z)**2)/A)+(a5/A**(1/2))
            C=B/A
            values.append(C)
            D=max(values)
            E=values.index(D) 
        maxvalues.append(D)    
        print ("the most stable nucleon for an atomic number",Z," has a nucleon number",E+Z,"and its binding energy per nucleon is",D,"mEv")
    F=max(maxvalues)
    G=maxvalues.index(F)
    print ("the most stable nucleon of them all has an atomic number",G,"and its binding energy per nucleon is",F,"mEv")

如您所见,此函数运行两个周期的计算,在它移动到下一个数字 Z 之前,它将该特定数字 Z 和多个 A's(range (Z, 3*Z+1)) 的所有结果存储到一个数组,然后找到最大值的索引并为那个特定的数字 Z 打印它,这里没问题。

但我想找到其中所有值最大的数字 Z。所以我让它重复每个数字 Z 的最大值的过程。

当我运行该函数时,它会打印所有数字 Z、其最稳定的同位素(数字 E+Z)和适当的结合能,即该特定数字 Z 的计算最大值和范围内的数字 A(Z,3 *Z+1)。作为最后一行,它应该打印出所有数字 Z 中值最大的数字 Z。程序说这个数字是 Z=27。然而,当我查看为所有数字 Z 打印的值时,我发现答案应该是 Z=28。为什么它不在输出的最后一行打印正确的数字 Z?

标签: pythonarraysfunctionindexingmax

解决方案


推荐阅读