Search code examples
pythonscipyminimization

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


Let's say I have this piece of code:

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

With such a constraint, I could restrict the result to be above 0:

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

But what if I want the value to be above 4? Is it possible to specify it?


Solution

  • Yes, it is possible. Just define your test function as:

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

    Alternatively, if you do not want to change the test function, define:

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