第五章5.4
學號後四位:3027
程式碼
點選檢視程式碼
import cvxpy as cp
import numpy as np
import pandas as pd
from scipy.optimize import minimize
import sympy as sp
sp.init_printing(use_unicode=True)
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['Times New Roman + SimSun + WFM Sans SC']
plt.rcParams['mathtext.fontset']='cm'
plt.rcParams['axes.unicode_minus']=False
plt.rcParams['figure.dpi'] = 200
plt.rcParams['xtick.direction'] = 'in'
plt.rcParams['ytick.direction'] = 'in'
a = np.arange(100, 0, -1)
x = cp.Variable(100, nonneg=True)
obj = cp.Maximize(cp.sum(cp.sqrt(x)))
cons = [
x[0] <= 10,
x[0] + 2*x[1] <= 20,
x[0] + 2*x[1] + 3*x[2] <= 30,
x[0] + 2*x[1] + 3*x[2] + 4*x[3] <= 40,
cp.sum(cp.multiply(a, x)) <= 1000,
]
prob = cp.Problem(obj, cons)
prob.solve(solver='ECOS')
print(f'最優解為:{x.value}'); print(f'最優值為:{prob.value}')`
5.5
程式碼
點選檢視程式碼
import cvxpy as cp
import numpy as np
import pandas as pd
from scipy.optimize import minimize
import sympy as sp
sp.init_printing(use_unicode=True)
import matplotlib.pyplot as plt
def obj(x):
x1, x2, x3 = x
return (-1)*(2*x1 + 3*x1**2 + 3*x2 + x2**2 + x3)
def ineq(x):
x1, x2, x3 = x
return [
10 - (x1 + 2*x1**2 + x2 + 2*x2**2 + x3),
50 - (x1 + x1**2 + x2 + x2**2 - x3),
40 - (2*x1 + x1**2 + 2*x2 + x3),
x1 + 2*x2 - 1,
]
def eq(x):
x1, x2, x3 = x
return x1**2 + x3 - 2
x0 = np.random.randn(3)
cons = [
{'type': 'ineq', 'fun': ineq},
{'type': 'eq', 'fun': eq},
]
bd = [(0, None), (None,None), (None, None)]
ret = minimize(obj, x0, constraints=cons, bounds=bd)
print(ret)
print('-'*100)
print("最優值為:", -ret.fun)