第三章作业3035
习题3.2
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 = sp.Function('x')
k = sp.symbols('k')
eq = x(k + 2) - x(k + 1) - 2 * x(k)
solution = sp.rsolve(eq, x(k), {x(0): -2, x(1): -2})
print("递归方程的通解:", solution)
习题3.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=':')
fig.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.35, hspace=None)
fig.show()