Search code examples
pythonode

System of First Order ODEs in Python


I have seen how to solve systems of ODEs in Python, but all of the examples I have seen were "standard" equations. What I mean by standard is that the equations do not say "derivative of one function = expression that contains derivative of another function".

Here is a sample system I am trying to solve numerically. Initial conditions are x(0) = 5, y(0) = 3, z(0) = 2, and all initial derivatives are 0:

x'(t) + 4y(t) = -3y'(t)

y'(t) + ty(t) = -2z'(t)

z'(t) = -2y(t) + x'(t)

I am not 100% sure how to code this. Here is what I have tried:

 import numpy as np
 from scipy.integrate import odeint
 import matplotlib.pyplot as plt
 import math

 def ODESystem(f,t):
     x = f[0]
     y = f[1]
     z = f[2]

Now, what do I define first: dydt, dxdt or dzdt. Is there a way for me to define one expression that "hangs around" before I use it to define another expression?


Solution

  • You do not need to solve anything manually, you can just as well do

    def ODESystem(f,t):
        x,y,z = f
        return np.linalg.solve([[1,3,0],[0,1,2],[-1,0,1]], [-4, -t, -2])*y