Python ode一阶,如何使用Sympy解决此问题 [英] Python ode first order, how to solve this using Sympy
本文介绍了Python ode一阶,如何使用Sympy解决此问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我尝试通过使用Sympy来解决这首歌时,如下所示:
When I try to solve this first ode by using Sympy as it shows below:
import sympy
y = sympy.Function('y')
t = sympy.Symbol('t')
ode = sympy.Eq(y(t).diff(t),(1/y(t))*sympy.sin(t))
sol = sympy.dsolve(ode,y(t))
csol=sol.subs([(t,0),(y(0),-4)]) # the I.C. is y(0) = 1
ode_sol= sol.subs([(csol.rhs,csol.lhs)])
print(sympy.pprint(ode_sol))
它给了我这个错误:
Traceback (most recent call last):
File "C:/Users/Mohammed Alotaibi/AppData/Local/Programs/Python/Python35/ODE2.py", line 26, in <module>
csol=sol.subs([(t,0),(y(0),-4)]) # the I.C. is y(0) = 1
AttributeError: 'list' object has no attribute 'subs'
推荐答案
您的问题是此ODE没有唯一的解决方案.因此,它返回解决方案列表,您可以从错误消息中找到并通过打印sol
来找到.
Your problem is that this ODE does not have a unique solution. Thus it returns a list of solution, which you can find out from the error message and by printing sol
.
循环执行评估,
for psol in sol:
csol = psol.subs([(t,0),(y(0),-4)]);
ode_sol = psol.subs([(csol.rhs,csol.lhs)]);
print(sympy.pprint(ode_sol))
查找下一个错误,该替换不能解决常量问题.有效的方法是定义C1=sympy.Symbol("C1")
并使用
to find the next error, that substituting does not solve for the constant. What works is to define C1=sympy.Symbol("C1")
and using
ode_sol= psol.subs([(C1, sympy.solve(csol)[0])]);
但是这仍然让人感觉很hack.或者更好地避免由于第二种情况无法解决而出现错误消息:
but this still feels hacky. Or better to avoid error messages for the unsolvability of the second case:
C1=sympy.Symbol("C1");
for psol in sol:
csol = psol.subs([(t,0),(y(0),-4)]);
for cc1 in sympy.solve(csol):
ode_sol= psol.subs([(C1, cc1)]);
print(sympy.pprint(ode_sol))
这篇关于Python ode一阶,如何使用Sympy解决此问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文