【发布时间】:2020-03-12 05:11:12
【问题描述】:
我已经实现了函数 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 函数,它期望 x 值的 numpy 数组作为其唯一参数。 begin_range, end_range - begin_range
返回 max_loc - 返回函数在 给定的范围。最大值的位置必须在以下范围内: begin_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
【问题讨论】:
标签: python python-3.x vectorization numpy-ndarray