【问题标题】:How to find maximum from given function with given range in python?python - 如何在给定范围内的给定函数中找到最大值?
【发布时间】: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


    【解决方案1】:

    试试这样:

    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
    

    【讨论】:

    • @MayurPotdar 查看我的更新 anwser 并检查公式是否仍然有效。
    • 谢谢,我想通了。我收到NameError: name 'numpy' is not defined 错误。但是,我已经导入了 numpy。
    • @MayurPotdar 我的错,我再次更新了我的 anwser,这个功能应该可以工作。命名空间中不存在 Numpy,因为我们已将其导入为 np
    猜你喜欢
    • 1970-01-01
    • 2022-12-04
    • 2021-02-11
    • 2017-09-04
    • 1970-01-01
    • 2013-09-09
    • 1970-01-01
    • 2016-07-15
    • 2019-12-31
    相关资源
    最近更新 更多