Boris Boris - 4 months ago 12
Python Question

Plotting in python using matplotlib?

I have been trying to simulate the first order differential equation using the fourth order Runge-Kutta method, but I am having problems plotting it.

#simulation of ode using 4th order rk method dy/dx=-2y+1.3e^-x,y(0)=5,h=0.01 from sympy import*
import math
import numpy as np
import matplotlib.pyplot as plt
h=0.01;
ti=0;
x=0;
n=0;
y=5;
def f(x,y):
return 1.3*math.exp(-x)-2*y


while x < 10:

k1=f(x,5);
k2=f(x+h/2,y+(h/2)* k1);
k3=f(x+h/2,y+(h/2)* k2);
k4=f(x+h,y+h*k3);
y=y+h/6*(k1+2*(k2+k3)+k4);
x=x+h;
plt.plot(x,y);


I know that the problem is because of updating the x,y values every time the loop runs, but can somebody explain how to plot all the values of (x,y)?

Answer

As suggested in the comment, you can create two lists to store x and y values and plot it after the while loop:

import math
import numpy as np
import matplotlib.pyplot as plt
h=0.01;
ti=0;
x=0;
n=0;
y=5;
def f(x,y):
    return 1.3*math.exp(-x)-2*y

xs = [x]       # <<<
ys = [y]       # <<<
while x < 10:

    k1=f(x,5);
    k2=f(x+h/2,y+(h/2)* k1);
    k3=f(x+h/2,y+(h/2)* k2);
    k4=f(x+h,y+h*k3);
    y=y+h/6*(k1+2*(k2+k3)+k4);
    x=x+h;
    xs.append(x)    # <<<
    ys.append(y)    # <<<

plt.plot(xs,ys);

enter image description here