Solving Linear ODE using Python

Improving the Efficiency

I took a hint from manual solution and implemented the following custom function InvLaplace to improve the efficiency by splitting expression using partial fractions and then finding inverse transforms term by term. Here we go:

from sympy import *
from sympy.integrals.transforms import laplace_transform, inverse_laplace_transform

s, L = symbols('s, L')
t= symbols ('t', positive =True)

def InvLaplace(expr):
	ans = 0
	part_frac = expr.apart()	# find partial fractions
	for term in part_frac.args:
		inv_term = inverse_laplace_transform(term,s,t,noconds=True)
		ans = ans + inv_term

y0  = 2
y10 = 1	# storing y(0) and y’(0)

Ly2 = s**2*L-s*y0-y10
Ly1= s*L-y0
Ly = L

algeq = Eq(Ly2 - Ly, laplace_transform(cos(t), t, s, noconds = True))

algsoln = solve(algeq, L)[0]
soln = InvLaplace(algsoln)
print("Solution: y(t) = ", soln)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.