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

使用SymPy求解二阶微分方程:让A2识别已求解的A1数值

问题分析与解决方案

你的代码里,A2的结果是1.33*A1而非数值,核心原因是你分开单独求解两个方程,解A2时没有将已求出的A1数值代入方程——此时方程里的A1还是最初定义的符号变量,不是你已经解出的-0.1。

两种解决方法:

方法一:联立方程组求解(推荐)

直接把两个初始条件方程组成方程组,一次性求解A1和A2,得到的就是具体数值解:

def A1_A2slvr():
    if(ωSquared > αSquared):
        print("Underdamped")
        ωD = math.sqrt(ωSquared - αSquared)
        α = math.sqrt(αSquared)
        e = math.e
        t = sp.symbols('t')
        A1 = sp.symbols('A1')
        A2 = sp.symbols('A2')

        #solving for constants A1 and A2
        VofT = (e**(-α*t)*(A1*sp.cos(ωD*t) + A2*sp.sin(ωD*t)) + vFinal)
        simpVofT = VofT.subs(t, 0).simplify()
        print(simpVofT)

        DVofT = sp.diff(VofT, t)
        simpDVofT = DVofT.subs(t, 0).simplify()
        print(simpDVofT)

        # 替换原有分步求解:联立两个方程求解A1、A2
        solution = sp.solve([simpVofT, simpDVofT], [A1, A2])
        A1_val = solution[A1]
        A2_val = solution[A2]
        print(A1_val)
        print(A2_val)

方法二:手动代入A1的解

如果要保留分步求解的逻辑,先把A1的解代入到A2的方程中,再求解:

def A1_A2slvr():
    if(ωSquared > αSquared):
        print("Underdamped")
        ωD = math.sqrt(ωSquared - αSquared)
        α = math.sqrt(αSquared)
        e = math.e
        t = sp.symbols('t')
        A1 = sp.symbols('A1')
        A2 = sp.symbols('A2')

        #solving for constants A1 and A2
        VofT = (e**(-α*t)*(A1*sp.cos(ωD*t) + A2*sp.sin(ωD*t)) + vFinal)
        simpVofT = VofT.subs(t, 0).simplify()
        print(simpVofT)

        DVofT = sp.diff(VofT, t)
        simpDVofT = DVofT.subs(t, 0).simplify()
        print(simpDVofT)

        # 先求解A1并取出具体值
        A1_val = sp.solve(simpVofT, A1)[0]
        # 将A1的数值代入A2的方程
        simpDVofT_updated = simpDVofT.subs(A1, A1_val)
        # 求解A2
        A2_val = sp.solve(simpDVofT_updated, A2)[0]
        print(A1_val)
        print(A2_val)

补充说明

之前用subs报错,大概率是因为你直接用了sp.solve返回的列表(A1)而非取出的具体值(A1[0])来替换。另外要确保vFinal、ωSquared、αSquared这些变量已经被赋值为具体数值,否则解出来的还是符号表达式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 08:02:42