Find the value of a variable that maximizes a multivariable function

Question:

I have a function like this:

def objective(x, y, z, q):
    theta1 = f(x, y)
    theta2 = f(x, z)
    rho = q - (theta1 + theta2)
    
    return rho * x

and I would like to find the value of x that maximizes the objective function, knowing that x must be between two boundaries b1, b2.

My first guess was to iterate from b1 through b2 to find which value of x maximizes the objective function but I guess there are more efficient ways to do this.

What is the most efficient way to find the value of x that maximizes the objective function in this case ?

I know I could use scipy.optimize.maximize, but I can’t find a way to use it to maximize the objective function with respect to just x.

Asked By: andiamo

||

Answers:

Assuming that x is a scalar variable and you already know the values of y, z and q, you could do something like this:

from scipy.optimize import minimize

# bound: b1 <= x <= b2
bounds = [(b1, b2)]

# given values for y, q, and z
y0 = 1.0 
z0 = 1.0
q0 = 1.0

# (feasible) initial guess
x0 = (b2 - b1) / 2.0

res = minimize(lambda x: -1.0*objective(x, y0, z0, q0), x0=x0, bounds=bounds)

Note that maximizing the function obj(x) is the equivalent to minimizing -1.0*obj(x).

Answered By: joni