98 lines
2.9 KiB
Python
98 lines
2.9 KiB
Python
# /// script
|
|
# requires-python = ">=3.11"
|
|
# dependencies = ["numpy", "matplotlib"]
|
|
# ///
|
|
|
|
import numpy as np
|
|
import matplotlib.pyplot as plt
|
|
|
|
# 设置中文字体
|
|
plt.rcParams['font.sans-serif'] = ['WenQuanYi Micro Hei', 'Noto Sans CJK SC', 'Microsoft YaHei', 'SimHei', 'SimSun', 'DejaVu Sans']
|
|
plt.rcParams['axes.unicode_minus'] = False
|
|
|
|
# 创建图形
|
|
fig, ax = plt.subplots(figsize=(10, 8), dpi=150)
|
|
|
|
# 定义函数 y = -2x² + 8x - 3
|
|
def f(x):
|
|
return -2*x**2 + 8*x - 3
|
|
|
|
# 顶点坐标
|
|
x_vertex = 2
|
|
y_vertex = 5
|
|
|
|
# 生成 x 值范围(以顶点为中心,左右各延伸适当距离)
|
|
x = np.linspace(-1, 5, 500)
|
|
y = f(x)
|
|
|
|
# 绘制抛物线
|
|
ax.plot(x, y, 'b-', linewidth=2.5, label=r'$y = -2x^2 + 8x - 3$')
|
|
|
|
# 标注顶点
|
|
ax.plot(x_vertex, y_vertex, 'ro', markersize=12, zorder=5, label=f'顶点 ({x_vertex}, {y_vertex})')
|
|
ax.annotate(f'顶点\n({x_vertex}, {y_vertex})',
|
|
xy=(x_vertex, y_vertex),
|
|
xytext=(x_vertex + 0.8, y_vertex + 0.5),
|
|
fontsize=12,
|
|
ha='left',
|
|
arrowprops=dict(arrowstyle='->', color='red', lw=1.5))
|
|
|
|
# 绘制对称轴
|
|
ax.axvline(x=x_vertex, color='green', linestyle='--', linewidth=1.5, alpha=0.7, label=f'对称轴 x = {x_vertex}')
|
|
|
|
# 绘制最大值水平线
|
|
ax.axhline(y=y_vertex, color='orange', linestyle=':', linewidth=1.5, alpha=0.7, label=f'最大值 y = {y_vertex}')
|
|
|
|
# 绘制坐标轴
|
|
ax.axhline(y=0, color='gray', linewidth=0.8)
|
|
ax.axvline(x=0, color='gray', linewidth=0.8)
|
|
|
|
# 求与 x 轴的交点(如果有)
|
|
# -2x² + 8x - 3 = 0
|
|
# x = (8 ± √(64-24)) / (-4) = (8 ± √40) / (-4)
|
|
discriminant = 64 - 24 # b² - 4ac = 64 - 24 = 40
|
|
x1 = (8 - np.sqrt(discriminant)) / 4
|
|
x2 = (8 + np.sqrt(discriminant)) / 4
|
|
ax.plot([x1, x2], [0, 0], 'g^', markersize=10, label=f'与x轴交点')
|
|
ax.annotate(f'({x1:.2f}, 0)', xy=(x1, 0), xytext=(x1-0.3, -1.5), fontsize=10, ha='center')
|
|
ax.annotate(f'({x2:.2f}, 0)', xy=(x2, 0), xytext=(x2+0.3, -1.5), fontsize=10, ha='center')
|
|
|
|
# 与 y 轴的交点
|
|
y_intercept = f(0)
|
|
ax.plot(0, y_intercept, 'ms', markersize=10, label=f'与y轴交点 (0, {y_intercept})')
|
|
|
|
# 设置坐标轴范围
|
|
ax.set_xlim(-1.5, 5.5)
|
|
ax.set_ylim(-5, 7)
|
|
|
|
# 设置网格
|
|
ax.grid(True, linestyle='--', alpha=0.5)
|
|
|
|
# 设置标签和标题
|
|
ax.set_xlabel('x', fontsize=14)
|
|
ax.set_ylabel('y', fontsize=14)
|
|
ax.set_title(r'二次函数 $y = -2x^2 + 8x - 3$ 的图像', fontsize=16, fontweight='bold')
|
|
|
|
# 添加图例
|
|
ax.legend(loc='lower right', fontsize=11)
|
|
|
|
# 添加关键信息文本框
|
|
textstr = '\n'.join([
|
|
r'$y = -2x^2 + 8x - 3$',
|
|
r'$= -2(x-2)^2 + 5$',
|
|
'',
|
|
f'顶点: (2, 5)',
|
|
f'最大值: 5',
|
|
f'对称轴: x = 2'
|
|
])
|
|
props = dict(boxstyle='round', facecolor='wheat', alpha=0.8)
|
|
ax.text(0.02, 0.98, textstr, transform=ax.transAxes, fontsize=11,
|
|
verticalalignment='top', bbox=props)
|
|
|
|
# 保存图像
|
|
plt.tight_layout()
|
|
plt.savefig('figure.png', bbox_inches='tight', dpi=150)
|
|
plt.close()
|
|
|
|
print("图像已保存: figure.png")
|