How to evaluate the constants SymPy gives with initial condition?

后端 未结 1 828
梦谈多话
梦谈多话 2020-12-18 07:23

How can I evaluate the constants C1 and C2 from a solution of a differential equation SymPy gives me? There are the initial condition f(0)=0 and f(pi/2)=3.

&         


        
1条回答
  •  旧巷少年郎
    2020-12-18 07:34

    There's a pull request implementing initial/boundary conditions, which was merged and should be released in SymPy 1.2. Meanwhile, one can solve for constants like this:

    sol = dsolve(f(x).diff(x,2)+f(x),f(x)).rhs
    constants = solve([sol.subs(x,0), sol.subs(x, math.pi/2) - 3])
    final_answer = sol.subs(constants)
    

    The code returns final_answer as 3.0*sin(x).

    Remarks

    solve may return a list of solutions, in which case one would have to substitute constants[0], etc. To force it to return a list in any case (for consistency), use dict=True:

    constants = solve([sol.subs(x,0), sol.subs(x, math.pi/2) - 3], dict=True)
    final_answer = sol.subs(constants[0])
    

    If the equation contains parameters, solve may or may not solve for the variables you want (C1 and C2). This can be ensured as follows:

    constants = solve([sol.subs(x,0), sol.subs(x, math.pi/2) - 3], symbols('C1 C2'))
    

    where again, dict=True would force the list format of the output.

    0 讨论(0)
提交回复
热议问题