You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用matplotlib绘制SymPy计算的导函数,解决表达式转float报错

错误原因
  • plt.plot() 仅支持数值类型的序列输入,你传入的derivative是sympy生成的符号表达式对象,matplotlib无法直接将符号表达式转换为浮点数值计算,因此触发报错。
  • 你直接传入单点计算结果derivative.subs(x,ex)给plt.plot()也无法正常绘图,plot方法需要成对的x坐标序列、y坐标序列才能生成曲线。
解决方案

你需要先将符号导数表达式转换为可做数值计算的函数,再生成连续的x取值序列,计算对应导数值后再绘图,修改后的完整代码如下:

import matplotlib.pyplot as plt
import numpy as np
import sympy as sp

# 原scipy.misc.derivative导入没有使用,且你后续用derivative做变量名会覆盖导入,因此删除该行
x = sp.Symbol("x")
ex = int(input("What is the value of x in f(x)? "))
coef = int(input("What is the coefficient of the first value? "))
if coef == 1:
    a = int(input("\nWhat is the value of the first coefficient in the equation? ")) #6
    sign = input("What is the operator of the equation? [+] or [-] ") #-
    expo = int(input("What is the value of exponent for the variable x? ")) #2
    ask = input("Does the 2nd value for the equation has constant? [Y] / [N]: ").upper() #y
    if ask == 'Y': #this will be the accepted condition for my example equation
        b = int(input("What is the value of constant? "))
        if sign == '-':
            f = a * x ** expo - b
        elif sign == '+':
            f = a * x ** expo + b
        derivative = sp.diff(f,x) # derivative of the function
        print (derivative) #prints the derivative as a function of x
        print (derivative.subs(x,ex)) # prints the derivative evaluated at x=3

        # 新增以下绘图逻辑
        # 1. 生成连续的x数值序列,区间可根据需要调整,这里取0到输入ex+2,共100个均匀采样点
        x_series = np.linspace(0, ex + 2, 100)
        # 2. 将符号导数表达式转换为支持numpy数值计算的函数
        f_prime = sp.lambdify(x, derivative, modules='numpy')
        # 3. 计算所有x点对应的导数值序列
        y_series = f_prime(x_series)
        # 4. 绘制导函数曲线
        plt.plot(x_series, y_series, label=f"导函数 f'(x)={derivative}")
        # 5. 单独标记x=ex处的计算点
        plt.scatter(ex, derivative.subs(x,ex), c='red', s=50, label=f"f'({ex})={derivative.subs(x,ex)}")
        # 添加辅助显示元素
        plt.legend()
        plt.grid(alpha=0.3)
        plt.xlabel("x")
        plt.ylabel("f'(x)")
        plt.show()
关键修改说明
  • 用sp.lambdify方法完成符号表达式到数值计算函数的转换,是sympy和数值计算库联动的标准用法
  • 新增了连续采样的x、y序列,满足matplotlib的绘图输入要求
  • 补充了单点标记、图例、坐标轴标注等元素,绘图结果可读性更强
  • 删除了未使用的scipy导数导入,避免变量名冲突

内容的提问来源于stack exchange,提问作者Maneki Autumn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 12:06:00