如何限制最小值高于特定值?

How to restrict minimized value to be above a specific value?

假设我有这段代码:

def test(params, *args):
    return params[0] + params[1]
minVal = minimize(test, [0.01, 0.02]) # I want minVal to be lowest non-negative value

有了这样的约束,我可以将结果限制在 0 以上:

# forces test(params) >= 0
con = [{"type" : "ineq", "fun" : test}]
minVal = minimize(test, x0=[0.01, 0.02], constraints=con)

但是如果我希望值大于 4 怎么办?可以指定吗?

是的,这是可能的。只需将 test 函数定义为:

def test(params, *args):
    return params[0] + params[1] - 4

或者,如果您不想更改 test 函数,请定义:

con = [{"type" : "ineq", "fun" : lambda x: test(x)-4}]
minVal = minimize(test, x0=[0.01, 0.02], constraints=con)