I am trying to implement euler method to solve differential equation y' = x^3 + y^2
between 0 and 2 with initial condition y(0) = 0.5
.
Firstly I set h = 0.1
and it's okey. y
converges to 643,....
Secondly I set h = 0.01
and y
diverges to the infinity.
Can anybody explain why this happen?
My MATLAB code is below:
clc;
clear;
close all;
% dy/dt = f(t, y)
f = @(t, y) t.^3 + y.^2;
a = 0;
ya = 0.5;
b = 2;
h = 0.1;
% h = 0.01;
M = (b-a)/h;
E = euler(f, a, b, ya, M);
function [E] = euler(f, a, b, ya, M)
% INPUT - f is the function
% - a and b are the left and right endpoints
% - ya is the initial condition y(a)
% - M is the number of steps
% OUTPUT - E = [T Y] where T is the vector of abscissas and
% Y is the vector of ordinates
h = (b-a) / M;
T = (a:h:b)';
Y = zeros(M+1, 1);
Y(1) = ya;
for j = 1:M
Y(j+1) = Y(j) + h*f(T(j), Y(j));
end
E = [T Y];
end