4.3
import numpy as np
import pandas as pd
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'
r = np.array([5, 28, 21, 23, 25])/100
q = np.array([0, 2.5, 1.5, 5.5, 2.6])/100
p = np.array([0, 1, 2, 4.5, 6.5])/100
u = np.array([0, 103, 198, 52, 40])
M = 1e4
x = cp.Variable(6, pos=True)
obj = cp.Minimize(x[-1])
k = 0.05
kk = []
P = []
X = []
while k < 0.27:
kk.append(k)
cons = [
cp.multiply(q[1:5], x[1:5]) <= x[-1],
(r-p) @ x[:-1] >= k*M,
(1+p) @ x[:-1] == M
]
prob = cp.Problem(obj, cons)
prob.solve(solver='GLPK_MI')
P.append(prob.value)
X.append(x.value)
k += 0.005
X = np.array(X)
fig = plt.figure(figsize=[6,2.5], dpi=500)
ax = fig.add_subplot(121)
ax.plot(kk, P, 'm', linewidth=3)
ax.grid(linestyle=':')
ax.set_xlabel('Profit degree')
ax.set_ylabel('Risk')
ax1 = fig.add_subplot(122)
for i in range(5):
ax1.plot(kk, (X.T)[i], label=f'$s_{i}$')
ax1.set_xlabel('Profit degree')
ax1.set_ylabel('Investment', labelpad=0)
ax1.legend(fontsize=7)
ax1.grid(linestyle=':')
#2022310143024
fig.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.35, hspace=None)
fig.show()
4.4
import numpy as np
import pandas as pd
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'
x = cp.Variable(2, integer=True)
c = np.array([[0, 5], [6, 2], [1, 1]])
b = np.array([15, 24, 5]).T
p = np.array([2, 1])
prob = cp.Problem(cp.Maximize(p @ x), [c@x <= b, x >= 0])
prob.solve(solver='GLPK_MI')
print(f'最优解为:{x.value}'), print(f'最优值为:{prob.value}')
print("2022310143024")
标签:plt,rcParams,np,array,cp,prob,第四章 From: https://www.cnblogs.com/yinhao3024/p/18510289