如何在 python 中的给定范围内从给定函数中找到最大值?

How to find maximum from given function with given range in python?

我已经实现了函数 find_maximum 和 f,即 returns 的值并将其作为参数传递给另一个函数,只是想找到给定函数的最大值。以下是我的实现。

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 < end_range 的实数值 定义我们想要确定的最大值的范围 内给定的功能。 step - 在范围内搜索的步长,默认为 0.001 的 最大值将被确定为该步长内的一个值,因此它 表示找到最大值的准确度。

Returns max_loc - returns函数最大的位置 给定的范围。最大值的位置必须在以下范围内: 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