![](/img/trans.png)
[英]How to find the maximum of a function given by a string in Python?
[英]How to find maximum from given function with given range in python?
我已經實現了函數 find_maximum 和 f,它們返回值並將其作為參數傳遞給另一個 function,並且只想找到給定 function 的最大值。 以下是我的實現。
import numpy as np
def find_maximum(f, begin_range, end_range, step=0.00001):
return np.maximum(begin_range, np.minimum(f, end_range))
def f(x):
myList = []
for i in range(1,4):
myList.append(0.3333* x**2) - 5*x - 3 + (numpy.cos(3)*x)
return myList
x = 4
print(find_maximum(f, -4, 4, 0.00001))
以下是更多解釋
f - 單個變量 f(x) 的矢量化 python function,它需要一個包含 x 值的 numpy 數組作為其唯一參數。 begin_range, end_range - begin_range < end_range 的實數值,定義我們想要確定給定 function 的最大值的范圍。 step - 在該范圍內搜索的步長,默認為 0.001 最大值將確定為此步長內的值,因此它表示找到最大值的精度。
返回 max_loc - 返回 function 在給定范圍內處於最大值的位置。 最大值的位置必須在范圍內:begin_range <= max_loc <= end_range
一個錯誤
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-b68bd5d55098> in <module>()
29 return myList
30 x = 4
---> 31 print(find_maximum(f, -4, 4, 0.00001))
<ipython-input-6-b68bd5d55098> in find_maximum(f, begin_range, end_range, step)
1 import numpy as np
2 def find_maximum(f, begin_range, end_range, step=0.00001):
----> 3 return np.maximum(begin_range, np.minimum(f, end_range))
4 '''Find the maximum of function f in the range [begin_range, end_range].
5 The function f should be a vectorized python function of a single
TypeError: '<=' not supported between instances of 'function' and 'int'
預期 output
print(find_maximum(f, -4, 4, 0.00001))
>>> -2.14085
試試這樣:
x = 4
print(find_maximum(f(x), -4, 4, 0.00001))
您需要先運行您的 function,然后再將其提供給 find_maximum
編輯:
你 function 少了一個括號:
def f(x):
myList = []
for i in range(1,4):
myList.append((0.3333* x**2) - 5*x - 3 + (np.cos(3)*x))
return myList
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.