实现一个SymPy脚本,自动求解并绘制给定符号表达式的极值点和拐点。

import sympy as sp
import matplotlib.pyplot as plt

# 定义符号变量
x = sp.symbols('x')

# 定义待分析的函数
def analyze_function(expr):
    # 计算一阶导数
    first_derivative = sp.diff(expr, x)
    # 计算二阶导数
    second_derivative = sp.diff(expr, x, 2)
    
    # 求解极值点(一阶导数为零的点)
    critical_points = sp.solve(first_derivative, x)
    # 求解拐点(二阶导数为零的点)
    inflection_points = sp.solve(second_derivative, x)
    
    # 绘制函数图像
    sp.plot(expr, (x, -10, 10), title='Function Plot', xlabel='x', ylabel='f(x)', line_color='blue')
    
    # 绘制极值点和拐点(如果存在)
    if critical_points:
        for point in critical_points:
            y = expr.subs(x, point)
            plt.scatter(point, y, color='red', label=f'Critical Point ({point}, {y})')
    if inflection_points:
        for point in inflection_points:
            y = expr.subs(x, point)
            plt.scatter(point, y, color='green', label=f'Inflection Point ({point}, {y})')
    
    # 显示图例
    plt.legend()
    plt.show()
    
    # 返回结果
    return {
        'critical_points': critical_points,
        'inflection_points': inflection_points,
        'first_derivative': first_derivative,
        'second_derivative': second_derivative
    }

# 示例:分析函数 f(x) = x^3 - 3x^2 + 2x
example_expr = x**3 - 3*x**2 + 2*x
result = analyze_function(example_expr)
print('极值点:', result['critical_points'])
print('拐点:', result['inflection_points'])
print('一阶导数:', result['first_derivative'])
print('二阶导数:', result['second_derivative'])

代码解析

1. 定义符号变量

使用 sympy.symbols 定义符号变量 x,用于表示函数的自变量。

2. 计算导数

  • 一阶导数通过 sp.diff(expr, x) 计算,用于寻找极值点。
  • 二阶导数通过 sp.diff(expr, x, 2) 计算,用于寻找拐点。

3. 求解极值点和拐点

  • 极值点:通过 sp.solve 解一阶导数为零的方程。
  • 拐点:通过 sp.solve 解二阶导数为零的方程。

4. 绘制函数图像

  • 使用 sp.plot 绘制函数的图像。
  • 使用 matplotlib.pyplot 绘制极值点和拐点,并用不同颜色标记。

5. 示例分析

分析函数 f(x) = x^3 - 3x^2 + 2x:

  • 极值点:解一阶导数 3x^2 - 6x + 2 = 0,得到 x ≈ 0.4226 和 x ≈ 1.5774。
  • 拐点:解二阶导数 6x - 6 = 0,得到 x = 1。

注意事项

  • 该脚本支持任意符号表达式,但复杂函数的求解可能需要调整绘图区间或数值求解。
  • 极值点和拐点的标记会在绘图时显示,便于直观理解。
  • 如果函数没有极值点或拐点,返回的空列表会被正确处理。