I am new to programmation and I tried to solve a maths optimization problem using Python.
The idea of the problem is to minimize the value of a function while some constraints are respected. This might seem very straightforward, however for some reason the result I get clearly does not satisfy the constraints.
The function in question is the following (I do not have enough reputation points to post images of LaTeX equations):
f(a,b,c,d) = 2*a + 3*b + c + 2*d
With the following constraints:
- a+b=2
- c+d=8
- a+c=3
- b+d=7
I used scipy.optimize.minimize in Python to try to solve it, here is my code:
import numpy as np
import scipy
from scipy.optimize import minimize as min
def f(x):
return 2*x[0] + 3*x[1] + x[2] + 2*x[3]
cons = ({'type' : 'eq','fun': lambda x: np.array([x[0]+x[1]-2])},
{'type' : 'eq','fun': lambda x: np.array([x[2]+x[3]-8])},
{'type':'eq' , 'fun': lambda x: np.array([x[0]+x[2]-3])},
{'type':'eq' , 'fun': lambda x: np.array([x[1]+x[3]-7])},
{'type':'ineq' , 'fun': lambda x: np.array([x[0]])},
{'type':'ineq' , 'fun': lambda x: np.array([x[1]])},
{'type':'ineq' , 'fun': lambda x: np.array([x[2]])},
{'type':'ineq' , 'fun': lambda x: np.array([x[3]])},
{'type':'ineq' , 'fun':f})
u = min(f,[1.5,0.5,1.5,6.5],constraints=cons,method='Nelder-Mead',options={'Disp':True,'maxiter':2})
print(u)
print(f(u.x))
It gives me some values for a,b,c,d that do not satisfy the equalities. I did try to change the optimization method but it did not help.
Any advice would be really appreciated, thank you for reading!