如何评估SymPy在初始条件下给出的常数? [英] How to evaluate the constants SymPy gives with initial condition?
问题描述
如何从SymPy给我的微分方程的解中求出常数C1和C2?有初始条件f(0)= 0和f(pi / 2)= 3。
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.
>>> from sympy import *
>>> f = Function('f')
>>> x = Symbol('x')
>>> dsolve(f(x).diff(x,2)+f(x),f(x))
f(x) == C1*sin(x) + C2*cos(x)
我尝试了一些 ics
的东西,但是没有用。示例:
I tried some ics
stuff but it's not working. Example:
>>> dsolve(f(x).diff(x,2)+f(x),f(x), ics={f(0):0, f(pi/2):3})
f(x) == C1*sin(x) + C2*cos(x)
顺便说一句:C2 = 0且C1 = 3。
By the way: C2 = 0 and C1 = 3.
推荐答案
有一个拉请求实现了初始/边界条件,该请求已合并并应在SymPy 1.2中发布。同时,可以这样求解常量:
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)
代码返回 final_answer
为 3.0 * sin(x)
。
solve
可能会返回解决方案列表,在这种情况下,必须替换 constants [0]
等。在任何情况下(出于一致性考虑)要强制其返回列表,请使用 dict = True
:
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])
如果方程式包含参数,则 solve
可能会或可能不会解决您想要的变量(C1和C2)。可以确保如下:
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'))
, dict = True
将强制输出的列表格式。
where again, dict=True
would force the list format of the output.
这篇关于如何评估SymPy在初始条件下给出的常数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!