Python ode first order, how to solve this using Sympy

断了今生、忘了曾经 提交于 2019-12-13 09:01:35

问题


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))

It gives me this error:

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'

回答1:


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.

Do the evaluation in a loop,

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))

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])]);

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))


来源:https://stackoverflow.com/questions/42038324/python-ode-first-order-how-to-solve-this-using-sympy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!