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

使用SymPy求解PDE触发TypeError,求代码修正方案及原因解释

求解波动方程时SymPy的TypeError问题

问题代码

from sympy import Function, Eq
from sympy.abc import x, t, L, c
from sympy.solvers.pde import pdsolve

f = Function('f')
u = Function('u')(x, t)
uxx = u.diff(x, x)
utt = u.diff(t, t)
eq = Eq(utt, c**2*uxx)

bc1 = Eq(u.subs(x, 0), 0)
bc2 = Eq(u.subs(x, L), 0)
ics = {u.subs(t, 0): f}

sol = pdsolve(eq, u, [bc1, bc2], ics=ics)

sol

报错信息

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[2], line 15
     12 bc2 = Eq(u.subs(x, L), 0)
     13 ics = {u.subs(t, 0): f}
---> 15 sol = pdsolve(eq, u, [bc1, bc2], ics=ics)
     17 sol

File c:\Users\MyName\AppData\Local\Programs\Python\Python311\Lib\site-packages\sympy\solvers\pde.py:169, in pdsolve(eq, func, hint, dict, solvefun, **kwargs)
    166     solvefun = Function('F')
    168 # See the docstring of _desolve for more details.
--> 169 hints = _desolve(eq, func=func, hint=hint, simplify=True,
    170                  type='pde', **kwargs)
    171 eq = hints.pop('eq', False)
    172 all_ = hints.pop('all', False)

File c:\Users\MyName\AppData\Local\Programs\Python\Python311\Lib\site-packages\sympy\solvers\deutils.py:232, in _desolve(eq, func, hint, ics, simplify, prep, **kwargs)
    229 if not hints['default']:
    230     # classify_ode will set hints['default'] to None if no hints match.
    231     if hint not in allhints and hint != 'default':
--> 232         raise ValueError("Hint not recognized: " + hint)
    233     elif hint not in hints['ordered_hints'] and hint != 'default':
    234         raise ValueError(string + str(eq) + " does not match hint " + hint)

TypeError: can only concatenate str (not "list") to str

修改后的代码

from sympy import Function, Eq
from sympy.abc import x, t, L, c
from sympy.solvers.pde import pdsolve

# 定义f为x的函数,而非抽象函数
f = Function('f')(x)
u = Function('u')(x, t)
uxx = u.diff(x, x)
utt = u.diff(t, t)
eq = Eq(utt, c**2*uxx)

bc1 = Eq(u.subs(x, 0), 0)
bc2 = Eq(u.subs(x, L), 0)
# 补充初始速度条件(波动方程为二阶时间导数,需两个初始条件)
ics = {u.subs(t, 0): f, u.diff(t).subs(t, 0): 0}

# 通过bc关键字参数传递边界条件
sol = pdsolve(eq, u, bc=[bc1, bc2], ics=ics)

print(sol)

修改原因

  1. 参数传递错误:pdsolve的第三个位置参数是hint(求解提示字符串),原代码直接将边界条件列表传入该位置,导致它被误判为hint参数,后续字符串拼接时触发TypeError。正确做法是通过bc关键字参数传递边界条件。
  2. 初始条件定义问题:原代码中f = Function('f')是抽象函数,而波动方程的初始位移应为x的具体函数,需改为f = Function('f')(x);同时波动方程是二阶时间导数,必须提供两个初始条件(位移和速度),这里补充了初始速度为0的条件。
  3. SymPy求解逻辑要求:针对带边界条件的波动方程,pdsolve需要通过关键字参数明确传入边界条件和初始条件,才能正确调用分离变量法完成求解。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 19:12:43