Search code examples
pythonnumpyscipydifferential-equations

How to solve a system of differential equations in Python?


How do we solve a system of linear equations in Python and NumPy:

We have a system of equations and there is the right side of the values after the equal sign. We write all the coefficients into the matrix matrix = np.array(...),, and write the right side into the vector vector = np.array(...) and then use the command np.linalg.solve(matrix, vector) to find the variables.

But if I have derivatives after the equal sign and I want to do the same with the system of differential equations, how can I implement this?

(Where are the lambda known values, and I need to find A

P.S. I saw the use of this command y = odeint(f, y0, t) from the library scipy but I did not understand how to set my own function f if I have a matrix there, what are the initial values y0 and what t?


Solution

  • You can solve your system with the compact form

    t = arange(t0,tf,h)
    solX = odeint(lambda X,t: M.dot(X), X0, t)
    

    after setting the parameters and initial condition.

    For advanced use set also the absolute and relative error thresholds according to the scale of the state vector and the desired accuracy.