我已经实现了函数find_maximum和f,它们返回值并将其作为参数传递给另一个函数,并且只想查找给定函数的最大值。以下是我的实现。
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函数,期望将numpy x值数组作为其唯一参数。begin_range,end_range-begin_range <end_range的实数值,定义一个范围,我们要确定该范围内给定函数的最大值。step-要在该范围内搜索的步长,默认值为0.001。最大值将确定为该步长范围内的值,因此它表示查找最大值的精度。
返回max_loc-返回函数在给定范围内最大的位置。最大值的位置必须在以下范围内: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'
预期产量
print(find_maximum(f, -4, 4, 0.00001))
>>> -2.14085
尝试这样:
x = 4
print(find_maximum(f(x), -4, 4, 0.00001))
您需要先运行函数,然后才能将其赋给find_maximum
编辑:
您的功能缺少括号:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句