如何从 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 在初始条件下给出的常数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!