第四章

4.3
import matplotlib.pyplot as plt
import numpy as np
import cvxpy as cp

x=cp.Variable(6,pos=True)
obj=cp.Minimize(x[5])
a1=np.array([0.025, 0.015, 0.055, 0.026])
a2=np.array([0.05, 0.27, 0.19, 0.185, 0.185])
a3=np.array([1, 1.01, 1.02, 1.045, 1.065])
k=0.05; kk=[]; qq=[]
while k<0.27:
con=[cp.multiply(a1,x[1:5])-x[5]<=0,a2@x[:-1]>=k, a3@x[:-1]==1]
prob=cp.Problem(obj,con)
prob.solve(solver='GLPK_MI')
kk.append(k); qq.append(prob.value)
k=k+0.005

plt.rc('text',usetex=False); plt.rc('font',size=16); plt.rc('font',family='SimHei')
plt.plot(kk,qq,'k')
plt.plot(kk,qq,'b.')
plt.xlabel("收益 k"); plt.ylabel("风险 Q",rotation=0)
plt.show()
print("3023")
结果

4.4
from scipy.optimize import linprog

c = [-2, -1]

A = [
[0, 5],
[6, 2],
[1, 1]
]
b = [15, 24, 5]

x_bounds = [(0, None), (0, None)]

result = linprog(c, A_ub=A, b_ub=b, bounds=x_bounds, method='highs')

print(f"Optimal value: {result.fun * -1:.2f}") # 因为linprog是最小化,所以结果要取反
print(f"x1: {result.x[0]:.0f}, x2: {result.x[1]:.0f}")
print("3023")
结果

posted @ 2024-10-22 16:57  cjl110  阅读(3)  评论(0编辑  收藏  举报