

import numpy as np
import matplotlib.pyplot as plt# 设置中文字体,确保中文显示正确
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用黑体显示中文
plt.rcParams['axes.unicode_minus'] = False # 正常显示负号# 设置图形和子图
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 12))# 函数1:f(x) = sin x
x1 = np.linspace(-2*np.pi, 2*np.pi, 1000)
y1 = np.sin(x1)ax1.plot(x1, y1, label='f(x) = sin x')
ax1.axhline(y=1, color='r', linestyle='--', label='上界:y = 1')
ax1.axhline(y=-1, color='g', linestyle='--', label='下界:y = -1')
ax1.set_title('f(x) = sin x 在 (-∞, +∞) 上')
ax1.set_xlabel('x')
ax1.set_ylabel('f(x)')
ax1.legend()
ax1.grid(True)# 函数2:f(x) = 1/x
x2_1 = np.linspace(0.05, 1, 1000) # 从0.05开始以避免极端值
y2_1 = 1/x2_1x2_2 = np.linspace(1, 2, 1000)
y2_2 = 1/x2_2ax2.plot(x2_1, y2_1, label='f(x) = 1/x 在 (0,1) 上')
ax2.plot(x2_2, y2_2, label='f(x) = 1/x 在 (1,2) 上')
ax2.axhline(y=1, color='r', linestyle='--', label='y = 1 (x ∈ (1,2) 的界)')
ax2.set_title('f(x) = 1/x 在 (0,1) 和 (1,2) 上')
ax2.set_xlabel('x')
ax2.set_ylabel('f(x)')
ax2.set_ylim(0, 3) # 限制y轴以提高可视性
ax2.set_xlim(0, 2) # 设置x轴限制
ax2.legend()
ax2.grid(True)plt.tight_layout()
plt.show()