|
本帖最后由 Nicolas2050 于 2020-2-2 18:35 编辑
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 5 14:16:13 2020
Problem: Nonlinear Optimization¶
Solve the following nonlinear optimization problem:
已知实数 x,y 满足 x(x+y)=1+2y^2 ,求 5x^2-4y^2 的最小值
⑴ min: 5x^2-4y^2
s.t.
-10≤x,y≤10
x(x+y)=1+2y^2
with initial conditions:
x0=(-1,1)
@author: NICOLAS TU
"""
from math import sqrt
import numpy as np
from scipy.optimize import minimize
def objective(x):
return 5*(x[0])**2-4*(x[1])**2
def constraint1(x):
sum_eq =1.0-(x[0])**2-(x[0]*x[1])+2*(x[1])**2
return sum_eq
# initial guesses
n = 2
x0 = np.zeros(n)
x0[0] =-1
x0[1] =1
# show initial objective
print('Initial Objective: ' + str(objective(x0)))
# optimize
b = (-10,10)
bnds = (b,b)
con1 = {'type': 'eq', 'fun': constraint1}
cons = ([con1])
solution = minimize(objective,x0,method='SLSQP',\
bounds=bnds,constraints=cons)
x = solution.x
# show final objective
print('Final Objective: ' + str(objective(x)))
# print solution
print('Solution')
print('x1 = ' + str(x[0]))
print('x2 = ' + str(x[1]))
'''
Initial Objective: 5.0
Final Objective: 3.9999653330068012
Solution
x1 = -0.999994960062743
x2 = -0.4999960669214395
''' |
|