jax
jax

Reputation: 840

Constrained Optimization with Scipy for a nonlinear fucntion

I am trying to maximize x^(0.5)y^(0.5) st. x+y=10 using scipy.

I can't figure out which method to use. I would really appreciate it if someone could guide me on this.

Upvotes: 1

Views: 167

Answers (1)

cel
cel

Reputation: 31379

Here are two possible ways:

The first version uses fmin_cobyla and therefore does not require the derivative of f.

from scipy.optimize import fmin_cobyla

f = lambda x : - (x[0]**0.5 * x[1]**(0.5))

# x + y = 10 <=> (x + y - 10 >= 0) & (-x -y + 10 >= 0)
c1 = lambda x: x[0] + x[1] - 10
c2 = lambda x: 10 - x[0] - x[1]

fmin_cobyla(f, [0,0], cons=(c1, c2))

And we get: array([ 4.9999245, 5.0000755])

The second version uses fmin_slsqp and exploits that we can calculate the partial derivatives analytically:

from scipy.optimize import fmin_slsqp

f = lambda x : - (x[0]**0.5 * x[1]**(0.5))

def f_prime(x):
    ddx1 = 0.5 * x[0]**-0.5 * x[1]**0.5
    ddx2 = 0.5 * x[1]**-0.5 * x[0]**0.5
    return [ddx1, ddx2]

f_eq = lambda x: x[0] + x[1] - 10

fmin_slsqp(f, [0.01,0.01], fprime=f_prime, f_eqcons=f_eq)

This is the output:

Optimization terminated successfully.    (Exit mode 0)
        Current function value: -5.0
        Iterations: 2
        Function evaluations: 2
        Gradient evaluations: 2

Upvotes: 4

Related Questions