Numpy 求解器:最大值
我有两个变量:
period(周期)和 result(结果)
我想知道怎么告诉 Numpy 这个工具(我想我需要用它)去找出能让我得到最高结果的 周期值?周期的范围必须在 1 到 100 之间。
编辑:
现在 周期 是 14 时,得到的 结果 是 40。
周期 是 12 时,得到的 结果 是 42。
我能不能让 Numpy 尝试从 1 到 100 之间的每一个 周期 值,然后只返回结果最好的那个?
我想我其实不一定需要 Numpy 来做这个,我在想这是否是一种可行的方法。
3 个回答
0
你手里具体有什么数据不太清楚,但这个方法应该可以用:
for period in periods:
result = func(period)
if result > resultmax:
resultmax = result
或者,如果 results
是一个 numpy.array
,并且 results[period]
是来自 period
的结果,那么你只需要这样做:
periodmax = results.argmax()
0
我不太确定我理解这个问题,但如果我理解对了的话,使用NumPy的索引可能是最好的选择:
period = NP.arange(50)
result = NP.random.randint(1, 101, 50)
q = NP.argmax(result) # gives index of largest value in the result array
result[q] # returns the highest value in the result array
period[q] # returns the value of period corresponding to
# the highest value for result
1
只需要先声明一个变量,把它的值设为第一个数字的周期值,然后自己写一个循环。在循环中,每当当前的数字比这个变量大时,就把这个变量的值更新为当前数字。
biggest = period(0)
index = 0
for i in range (1, 100)
if period(i) > biggest
biggest = period(i)
index = i
return biggest