TransWikia.com

Solution of Coupled Differential equation for a 2d linear flow using RK4 method in python 3

Computational Science Asked by Anirban Majumdar on March 1, 2021

I want to study the dynamics of a 2d linear flow, whose dynamical equation is- $begin{pmatrix} dot{x_1} dot{x_2} end{pmatrix}=begin{pmatrix} 1 & 1 4 & -2 end{pmatrix}begin{pmatrix} x_1 x_2 end{pmatrix}$. Now I have tried to solve and plot y vs. x of this coupled differential equation using RK4 in python for the initial condition $(y_0=2, x_0=-1)$. My code is following, but the graph is not correct [In the graph origin should be a saddle point, $begin{pmatrix} -0.25 1 end{pmatrix}$ axis should be stable manifold and $begin{pmatrix} 1 1 end{pmatrix}$ axis should be unstable manifold]-

import numpy as np
from math import sqrt

import matplotlib.pyplot as plt



# Equations:
   
def V(u,t):
    x1, x2, v1, v2 = u
    return np.array([ v1, v2, (x1+x2), -(4*x1-2*x2)])

def rk4(f, u0, t0, tf , n):
    t = np.linspace(t0, tf, n+1)
    u = np.array((n+1)*[u0])
    h = t[1]-t[0]
    for i in range(n):
        k1 = h * f(u[i], t[i])    
        k2 = h * f(u[i] + 0.5 * k1, t[i] + 0.5*h)
        k3 = h * f(u[i] + 0.5 * k2, t[i] + 0.5*h)
        k4 = h * f(u[i] + k3, t[i] + h)
        u[i+1] = u[i] + (k1 + 2*(k2 + k3) + k4) / 6
    return u, t


u, t  = rk4(V, np.array([2.0, 0., -1, 1.]) , 0. , 1. , 1000)
x1, x2, v1, v2 = u.T
plt.plot(x1,x2)
plt.show()

Can anyone helps me to write this code.

One Answer

You are implementing the system $$ pmatrix{ddot x_1ddot x_2} = pmatrix{1&1-4&2} pmatrix{x_1x_2} $$ in its first-order version with $v_k=dot x_k$. It is not surprising that this different system results in different solutions.

For your stated system you would have to use

def V(u,t):
    x1, x2 = u
    return np.array([  (x1+x2), (4*x1-2*x2)])

The difference in state space dimension should be readily noticeable.

Correct answer by Lutz Lehmann on March 1, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP