0

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)?

3
  • Try to gather (x,y) values in a list (or two lists, depends on your plot). Then, plot the data list once. Commented Jul 16, 2016 at 14:59
  • let me try @MichaelHoff Commented Jul 16, 2016 at 15:00
  • For example, this tutorial shows the use of data points together with matplotlib.plot. Commented Jul 16, 2016 at 15:05

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

This is a minor comment but you might want to also add the initial condition to your x/y-values.
@pathoren Considering the amount of points OP has, it doesn't make much difference to add another point, but good catch!
Add this line on the top of your script: %matplotlib inline if you are using ipython/jupyter notebook.
0

Another source for wrong results is the first line in the RK4 loop. Instead of

    k1=f(x,5);

use

    k1=f(x,y);

since the value of y does not stay constant at the initial value.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.