Numerical Methods for DEs Example
Consider the initial value problem: y 0 = 2x(1 + y 2 ), y(0) = 0 . We’ll use Matlab to
approximate the solution of this IVP (to Matlab’s default of 4 decimal places) on the
interval [0, 1] with step size h = 0.1 using Euler’s Method, the Improved Euler’s Method
and the Rung-Kutta Method of order 4. The true solution is y(x) = tan(x2 ) .
Here is the Matlab m-file that does the calculations and produces the graph of the results.
%% Matlab m-file %%
%% Example: y' = 2x (1+y^2), y(0) = 0, h = 0.1, [0,1] %%
%% set initial conditions %%
x(1) = 0;
y(1) = 0;
%% Matlab requires indices to start at 1 %%
%% Euler's Method %%
for n = 1:10
y(n+1) = y(n) + 2*(0.1)*x(n)*(1+y(n)^2);
yeuler(n) = y(n+1);
x(n+1) = x(n) + 0.1;
ytrue(n) = tan(x(n+1)^2);
eulererr(n) = abs(ytrue(n)-yeuler(n));
end
%% Improved Euler's Method %%
yc(1) = 0;
for n = 1:10
yp(n+1) = yc(n) + 2*(0.1)*x(n)*(1+yc(n)^2);
yc(n+1) = yc(n) + (0.1)*(x(n)*(1+yc(n)^2)+x(n+1)*(1+yp(n+1)^2));
yimpeuler(n) = yc(n+1);
impeulererr(n) = abs(ytrue(n)-yimpeuler(n));
end
%% Runge-Kutta Method of order 4 %%
for n = 1:10
k1 = 2*(0.1)*x(n)*(1+y(n)^2);
k2 = 2*(0.1)*(x(n)+0.05)*(1+(y(n)+(0.5)*k1)^2);
k3 = 2*(0.1)*(x(n)+0.05)*(1+(y(n)+(0.5)*k2)^2);
k4 = 2*(0.1)*(x(n)+0.1)*(1+(y(n)+k3)^2);
y(n+1) = y(n) + (1/6)*(k1+2*k2+2*k3+k4);
yrk4(n) = y(n+1);
rk4err(n) = abs(ytrue(n)-yrk4(n));
end
%% Matlab's deafult is to give results with 4 digits after the decimal %%
%% Plot the results %%
w = 0:0.01:1;
z = 0.1:0.1:1;
plot(w,tan(w.^2),z,yeuler,'+r',z,yimpeuler,'sm',z,yrk4,'*b')
legend('tan(x^2)','Euler','Improved Euler','RungeKutta','Location','Northwest')
xlabel('x')
ylabel('y')
Here is the graph of the results from Matlab. The curve is the true solution. The points
are the values from the numerical methods.
1.6
tan(x2)
Euler
Improved Euler
Runge−Kutta
1.4
1.2
y
1
0.8
0.6
0.4
0.2
0
0
0.1
0.2
0.3
0.4
0.5
x
0.6
0.7
0.8
0.9
1
Here are the numerical results.
x
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0
y(x)
0.0100
0.0400
0.0902
0.1614
0.2553
0.3764
0.5334
0.7445
1.0505
1.5574
Euler
0
0.0200
0.0600
0.1202
0.2014
0.3054
0.4366
0.6033
0.8216
1.1231
Error
0.0100
0.0200
0.0302
0.0412
0.0539
0.0710
0.0968
0.1412
0.2289
0.4343
Imp. Euler
0.0100
0.0400
0.0902
0.1614
0.2554
0.3765
0.5335
0.7441
1.0471
1.5387
Error
0
0
0
0
0.0001
0.0001
0.0001
0.0004
0.0034
0.0187
Runge-Kutta
0.0100
0.0400
0.0902
0.1614
0.2553
0.3764
0.5334
0.7446
1.0505
1.5574
Error
0
0
0
0
0
0
0
0.0001
0
0
© Copyright 2026 Paperzz