习题6.4代码
import numpy as np
import pandas as pd
import cvxpy as cp
import networkx as nx
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['Times New Roman + SimSun + WFM Sans SC']
plt.rcParams['mathtext.fontset']='stix'
Times New Roman + SimSun + WFM Sans SC
simsum宋体, times new roman -*, simhei黑体, kaiti楷体,
dengxian等线, fangsong仿宋, Microsoft Yahei微软雅黑
plt.rcParams['axes.unicode_minus']=False
plt.rcParams['figure.dpi'] = 200
plt.rcParams['figure.figsize'] = [4, 3]
plt.rcParams['font.size'] = 12
plt.rcParams['xtick.direction']='in'
plt.rcParams['ytick.direction']='in'
price = np.array([2.5, 2.6, 2.8, 3.1])
sell = np.array([2.0, 1.6, 1.3, 1.1])
cost = np.array([0.3, 0.8, 1.5, 2.0])
cumsum_cost = np.cumsum(cost)
year_num = 4
W = np.zeros((year_num+1, year_num+1))
for i in range(year_num+1):
W[i,i] = 0
for i in range(year_num+1):
for j in range(i+1, year_num+1):
W[i, j] = price[i] + cumsum_cost[j-i-1] - sell[j-i-1]
W[np.isinf(W)] = 0
G = nx.DiGraph(W)
path = nx.shortest_path(G, 0, year_num, weight='weight')
dis = nx.shortest_path_length(G, 0, year_num, weight='weight')
print("应当在以下年份购置新设备", np.array(path[:-1]) + 1)
print("最少费用", round(dis,1))