0

I am trying to minimize the function

20A + 40B subject to 120 = 100sqrt(A) + 150sqrt(B)

I wrote the following code and used it with other functions and it worked. But this time it doesn't with math.sqrt.

from scipy.optimize import minimize
from math import sqrt
import numpy as np


def U(args):  
    A, B = args
    return 20*A+40*B 

def constraint(args):
    A, B = args
    return  120-100*sqrt(A)-150*sqrt(B)

con = {'type':'eq','fun':constraint}  
result1 = minimize(U, x0 = [0.1, 0.1], method='SLSQP', constraints=con)
print(f'Optimal_A is {result1.x[0]:.2f} and optimal_B is {result1.x[1]:.2f}')

I was able to solve this correctly using np.sqrt instead of math.sqrt. What's going on here? Thanks a lot.

1 Answers1

0

I haven’t tried your example, but is it possible that SLSQP is stepping into negative values for A or B? Since the constraint takes the square root of them, I’d suggest putting bounds on A and B to be non-negative.

Infinity77
  • 1,317
  • 10
  • 17