45 lines
1.1 KiB
Python
45 lines
1.1 KiB
Python
# /// script
|
||
# requires-python = ">=3.11"
|
||
# dependencies = ["sympy"]
|
||
# ///
|
||
|
||
import sympy as sp
|
||
|
||
# 定义符号(实数)
|
||
x = sp.symbols("x", real=True)
|
||
|
||
# 定义函数
|
||
y = -2 * x**2 + 8 * x - 3
|
||
|
||
# 方法1:通过顶点公式求解
|
||
# 二次函数 y = ax^2 + bx + c 的顶点公式:x = -b/(2a)
|
||
a = -2
|
||
b = 8
|
||
c = -3
|
||
|
||
x_vertex = -b / (2 * a)
|
||
y_vertex = a * x_vertex**2 + b * x_vertex + c
|
||
|
||
# 方法2:通过求导验证
|
||
dy_dx = sp.diff(y, x)
|
||
critical_points = sp.solve(dy_dx, x)
|
||
d2y_dx2 = sp.diff(dy_dx, x)
|
||
|
||
print("=" * 50)
|
||
print("二次函数:y = -2x² + 8x - 3")
|
||
print("=" * 50)
|
||
|
||
print("\n【方法1:顶点公式】")
|
||
print(f"顶点坐标:({x_vertex}, {y_vertex})")
|
||
|
||
print("\n【方法2:求导法】")
|
||
print(f"导数:y' = {dy_dx}")
|
||
print(f"二阶导数:y'' = {d2y_dx2}")
|
||
print(f"临界点:x = {critical_points[0]}")
|
||
print(f"代入原函数:y = {y.subs(x, critical_points[0])}")
|
||
print(f"二阶导数:{d2y_dx2} < 0,故为极大值点")
|
||
|
||
print("\n【结论】")
|
||
print(f"1. 顶点坐标:({x_vertex}, {y_vertex})")
|
||
print(f"2. 函数最大值:{y_vertex}")
|