[英]How to find a max value
我是python的新手,正在嘗試與newmans計算物理學一起學習它。 我試圖編寫一個程序來解決其中一個練習。 它是使用近似公式計算最高結合能的。 我編寫了這個程序,以查找綁定能量:
from numpy import *
Z=int(raw_input("What is the atomic number?"))
a1,a2,a3,a4 = 15.67,17.23,0.75,93.2
for A in range(Z, 3*Z):
if A%2==1:
a5=0
elif A%2==0 and Z%2==0:
a5=12.0
elif A%2==0 and Z%2==1:
a5=-12.0
B=a1*A-a2*A**(2/3.0)-a3*Z**2/A**(1/3.0)-a4*(A-2*Z)**2/A+a5/A**(1/2.0)
print B
我的問題是找到B的最大值。我嘗試使用列表,數組和max函數。
將您的代碼放入函數binding_energy
,以Z
作為參數:
def binding_energy(Z):
a1,a2,a3,a4 = 15.67,17.23,0.75,93.2
for A in range(Z, 3*Z):
if A%2==1:
a5=0
elif A%2==0 and Z%2==0:
a5=12.0
elif A%2==0 and Z%2==1:
a5=-12.0
B=a1*A-a2*A**(2/3.0)-a3*Z**2/A**(1/3.0)-a4*(A-2*Z)**2/A+a5/A**(1/2.0)
yield B
然后它將返回結果的生成器,您可以使用max()
獲得最大值B
:
>>> max(binding_energy(Z))
如果您想找出A
哪個值使B
最大化,則替換
yield B
與
yield (A, B)
您可以from numpy import *
刪除from numpy import *
除非您在其他地方使用它。 除此之外,使用列表也可以。 要獲得最大值,只需調用max(B),如下所示:
Z=int(raw_input("What is the atomic number?"))
a1,a2,a3,a4 = 15.67,17.23,0.75,93.2
B = []
for A in range(Z, 3*Z):
if A%2==1:
a5=0
elif A%2==0 and Z%2==0:
a5=12.0
elif A%2==0 and Z%2==1:
a5=-12.0
num = a1*A-a2*A**(2/3.0)-a3*Z**2/A**(1/3.0)-a4*(A-2*Z)**2/A+a5/A**(1/2.0)
print num
B.append(num)
print max(B)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.