Files
2026-01-09 17:01:17 +08:00

72 lines
1.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# /// script
# requires-python = ">=3.11"
# dependencies = ["sympy"]
# ///
import sympy as sp
# 定义符号变量
x = sp.symbols('x', real=True)
# 定义二次函数
y = -2*x**2 + 8*x - 3
print("=" * 50)
print("二次函数 y = -2x² + 8x - 3 求解")
print("=" * 50)
# 方法1配方法求顶点
# y = -2(x² - 4x) - 3
# y = -2(x² - 4x + 4 - 4) - 3
# y = -2(x - 2)² + 8 - 3
# y = -2(x - 2)² + 5
# 方法2使用公式 x_vertex = -b/(2a)
a = -2
b = 8
c = -3
x_vertex = -b / (2*a)
y_vertex = a * x_vertex**2 + b * x_vertex + c
print(f"\n1. 顶点坐标")
print(f" 使用公式 x = -b/(2a) = -{b}/(2×{a}) = {x_vertex}")
print(f" 代入求 y = {a}×{x_vertex}² + {b}×{x_vertex} + ({c}) = {y_vertex}")
print(f" 顶点坐标: ({int(x_vertex)}, {int(y_vertex)})")
print(f"\n2. 函数最大值")
print(f" 由于 a = {a} < 0抛物线开口向下")
print(f" 函数在顶点处取得最大值")
print(f" 最大值: y_max = {int(y_vertex)}")
# 使用 SymPy 验证
print("\n" + "=" * 50)
print("SymPy 符号计算验证")
print("=" * 50)
# 求导数找极值点
dy = sp.diff(y, x)
critical_points = sp.solve(dy, x)
print(f"\n导数: y' = {dy}")
print(f"令 y' = 0解得 x = {critical_points}")
# 验证是最大值(二阶导数 < 0
d2y = sp.diff(dy, x)
print(f"二阶导数: y'' = {d2y} < 0确认为最大值点")
# 计算顶点处的函数值
x_v = critical_points[0]
y_v = y.subs(x, x_v)
print(f"\n顶点坐标: ({x_v}, {y_v})")
print(f"最大值: {y_v}")
# 配方形式
print("\n" + "=" * 50)
print("配方形式验证")
print("=" * 50)
vertex_form = -2*(x - 2)**2 + 5
expanded = sp.expand(vertex_form)
print(f"配方形式: y = -2(x - 2)² + 5")
print(f"展开验证: {expanded}")
print(f"与原式相等: {sp.simplify(expanded - y) == 0}")