我正在編寫一個程序,它求解區(qū)間 0:9 內(nèi)的函數(shù),其中步長為 0.005。該程序需要 1800 次計算,并需要一種方法來查找所使用的函數(shù)和 x 參數(shù)的最大值。為了計算函數(shù) 1800 次 (9/0.005)、找到它的最大值并輸出用于計算最大值的相關(guān)參數(shù)值,推薦使用的方法和循環(huán)是什么?我的想法是應(yīng)該生成 2 個列表,一個用于范圍/間隔(1800 個項目),另一個用于計算值(也是 1800 個)。然后使用列表索引或其他方法在“計算數(shù)組”中找到 max 并在另一個數(shù)組中找到相關(guān)的 x 參數(shù)。from operator import itemgetterimport mathmyfile = open("result.txt", "w")data = []step=0.005rng=9lim=rng/stepprint(lim)xs=[x * step for x in range(rng)]lim_int=int(lim)print(xs)for i in range(lim_int): num=itemgetter(i)(xs) x=math.sin(num)* math.exp(-num/100) print(i, x) data.append(x)for i in range(rng): text = str(i) text2 = str(data[i]) print(text, text2) myfile.write(text + ' ' + text2 + '\n')i=1while i < rng: i=i+1 num2=itemgetter(i)(xs) v=math.sin(num2)* math.exp(-num2/100) if v==max(data): arg=num2 breakprint('largest function value', max(data))print('function argument value used', arg)myfile.close()
1 回答

繁花如伊
TA貢獻2012條經(jīng)驗 獲得超12個贊
Numpy 是廣泛使用的高性能包:
import numpy as np
x = np.arange(0, 9, 0.005)
f = np.sin(x)*np.exp(-x/100)
print("max is: ", np.max(f))
print("index of max is: ", np.argmax(f))
輸出:
max is: 0.98446367206362
index of max is: 312
如果由于某種原因你想要一個原生的 python 解決方案(不使用 list 方法max和index),你可以這樣做:
step = 0.005
rng = 9
lim = int(rng/step)
x = [x_i*step for x_i in range(lim + 1)]
f = [math.exp(-x_i/100)*math.sin(x_i) for x_i in x]
max_ind = 0
f_max = f[max_ind]
for j, f_x in enumerate(f):
if f_x > f_max:
f_max = f_x
max_ind = j
添加回答
舉報
0/150
提交
取消