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

Python用sympy库求导时报str无diff属性AttributeError如何解决

错误根因

sanitiseFunction 方法返回的是字符串类型,而 diff 是sympy表达式对象的专属方法,无法被字符串调用,因此抛出属性错误。除此之外原有清洗函数还存在隐藏bug:判断x前字符是否为数字时直接调用int()转换,若x前不是数字或者x位于表达式开头时会直接抛出转换异常。

修复方案

  1. 清洗后的格式化字符串需通过sym.sympify()方法转换为sympy可识别的表达式对象,再调用求导方法
  2. 优化清洗逻辑,用isdigit()方法判断x前字符是否为数字,避免类型转换报错

修复后完整代码

import sympy as sym

x = sym.Symbol('x')

def sanitise_function(f: str) -> str:
    f = f.strip()
    # 处理开头为x的情况,补系数1
    if f.startswith("x"):
        f = "1" + f
    cleaned = ""
    for pos in range(len(f)):
        current_char = f[pos]
        # 当前字符是x,且前一个字符是数字的情况补乘号
        if current_char == "x" and pos > 0 and f[pos-1].isdigit():
            cleaned += "*"
        cleaned += current_char
    # 替换幂次符号为sympy兼容格式
    cleaned = cleaned.replace("^", "**")
    return cleaned

def symbolic_differentiation(input_f: str):
    formatted_str = sanitise_function(input_f)
    # 字符串转sympy表达式对象
    sym_expr = sym.sympify(formatted_str)
    derivative_f = sym_expr.diff(x)
    return derivative_f

if __name__ == "__main__":
    f = input("Enter the function: ")
    print(symbolic_differentiation(f))

测试效果

输入 3x^3,程序输出 9*x**2,符合需求。

内容的提问来源于stack exchange,提问作者Sam Paine

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 19:24:02