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)?
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);
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.