mtba
mtba

Reputation: 13

Python ode first order, how to solve this using 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))

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'

Upvotes: 0

Views: 398

Answers (1)

Lutz Lehmann
Lutz Lehmann

Reputation: 25992

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

Upvotes: 1

Related Questions