Search code examples
pythonminimize

Minimizing a function while keeping some of the variables constant


I have a function of the form

def tmp(x,n):
    R, s, a, T = x[0], x[1], x[2], x[3]

which returns a float, after a long block of calculations.

I need to minimize this function and for that I used the scipy.optimize.minimize():

minimize(tmp,[0,0,3,60000], args=(n,),tol =1e-15)

The above code looks for the minimum of the function tmp() with the starting values as shown.

Now I need to minimize the same function tmp, but keeping the variables R,T out of the minimization, as parameters. In other words I want the function to be written like:

def tmp(x,n,R,T):
        s, a = x[0], x[1]

How is it possible to create a function like the above without editing my first function?


Solution

  • Not knowing what ist going on in your function makes it difficult to test something... Where do you define R, s, a and T...inside the function?

    couldn´t you write a function like:

    def tmp(x,n,cons):
           if cons is False:#case 1
               R, s, a, T = x[0], x[1], x[2], x[3]
           elif cons is True:#case 2
               R=0 #change them if you want 
               T=60000
               s, a = x[0], x[1]
           #your calculations
           #...
    

    than you have to remember (!) that your "minimize" has to look like that for case one:

    minimize(tmp,[0,0,3,60000], args=(n,cons),tol =1e-15)#where args is (2,False) for example
    

    and like this for case 2:

    minimize(tmp,[0,3], args=(n,cons),tol =1e-15)#where args is (2,True)