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

在python中,如何从给定范围的给定函数中找到最大值?,python,python-3.x,vectorization,numpy-ndarray,Python,Python 3.x,Vectorization,Numpy Ndarray,我已经实现了find_max和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):

我已经实现了find_max和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-返回函数在中处于最大值的位置 给定的范围。最大值的位置必须在以下范围内: 开始\u范围像这样尝试:

x=4
打印(查找最大值(f(x),-4,4,0.00001))
您需要先运行函数,然后再赋予它以找到_最大值

编辑:

函数缺少括号:

def(x):
myList=[]
对于范围(1,4)内的i:
myList.append((0.3333*x**2)-5*x-3+(np.cos(3)*x))
返回myList

@MayurPotdar查看我的最新版本anwser并检查公式是否仍然有效。谢谢,我找到了答案。我得到
namererror:name'numpy'未定义
Error。但是,我已经导入了numpy。@MayurPotdar我的坏,我已经再次更新了我的anwser,这个函数应该可以工作。名称空间中不存在Numpy,因为我们已将其作为np导入
---------------------------------------------------------------------------
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