第三章

3.2
import sympy as sp
def solve_difference_equation():
n = sp.symbols('n', integer=True)
x = sp.Function('x')
eq = sp.Eq(x(n + 2) - x(n + 1) - 2 * x(n), 0)
sol = sp.rsolve(eq, x(n), {x(0): -2, x(1): -2})
return sol

solution = solve_difference_equation()
print(solution)
print("3023")

3.4
import numpy as np
from scipy.sparse.linalg import eigs
import matplotlib.pyplot as plt

adjacency_matrix = np.array([
[0, 1, 0, 1, 1, 1],
[0, 0, 0, 1, 1, 1],
[1, 1, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 1],
[0, 0, 1, 0, 0, 1],
[0, 0, 1, 0, 0, 0]
])

out_degree = np.sum(adjacency_matrix, axis=1, keepdims=True)

num_nodes = adjacency_matrix.shape[0]

damping_factor = 0.85

transition_matrix = (1 - damping_factor) / num_nodes + damping_factor * adjacency_matrix / out_degree

eigenvalue, eigenvector = eigs(transition_matrix.T, k=1, which='LR') # 'LR' 表示求最大实部特征值

eigenvector = eigenvector.flatten().real / np.sum(eigenvector.flatten().real)

print("最大特征值为:", eigenvalue.real[0])
print("归一化特征向量为:\n", np.round(eigenvector, 4))

plt.bar(range(1, num_nodes + 1), eigenvector, width=0.6)
plt.xlabel('节点')
plt.ylabel('PageRank值')
plt.title('PageRank分布')
plt.show()
print("3023")


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