1 2 3 4 5 6 7 8 9 10 11 12 13
| def minimize(fun: Callable, x0: ndarray, args: Union[Iterable, tuple, None] = (), method: Union[str, Callable, None] = None, jac: Union[Callable, str, bool, None] = None, hess: str = None, hessp: Optional[Callable] = None, bounds: Union[Iterable, Bounds, None] = None, constraints: Optional[dict] = (), tol: Optional[float] = None, callback: Optional[Callable] = None, options: Optional[dict] = None) -> Any #Minimization of scalar function of one or more variables.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| from scipy import optimize as opt import numpy as np from scipy.optimize import minimize
def objective(x): return x[0] ** 2 + x[1]**2 + x[2]**2 +8
def constraint1(x): return x[0] ** 2 - x[1] + x[2]**2 def constraint2(x): return -(x[0] + x[1]**2 + x[2]**2-20) def constraint3(x): return -x[0] - x[1]**2 + 2 def constraint4(x): return x[1] + 2*x[2]**2 -3
b = (0.0, None) bnds = (b, b ,b)
con1 = {'type': 'ineq', 'fun': constraint1} con2 = {'type': 'ineq', 'fun': constraint2} con3 = {'type': 'eq', 'fun': constraint3} con4 = {'type': 'eq', 'fun': constraint4}
cons = ([con1, con2, con3,con4])
solution = minimize(objective, x0, method='SLSQP', bounds=bnds, constraints=cons) x = solution.x print(solution) print('目标值: ' + str(objective(x))) print('答案为') print('x1 = ' + str(x[0])) print('x2 = ' + str(x[1]))
|
fun: 10.651091840572583
jac: array([1.10433471, 2.40651834, 1.89564812])
message: 'Optimization terminated successfully'
nfev: 71
nit: 15
njev: 15
status: 0
success: True
x: array([0.55216734, 1.20325918, 0.94782404])
目标值: 10.651091840572583
答案为
x1 = 0.5521673412903173
x2 = 1.203259181851855