% Eulerian Method
% Setup and initial conditions
H = [0.25 0.1 0.05 0.01 0.005]; % step size
Y_euler = cell(1,numel(H));
for k=1:numel(H)
h = H(k);
x = 0:h:5; % interval of x
y = zeros(1, numel(x)); % allocate the resulting y
y(1) = 1; % inizial value of y
n = numel(y); % the number of y values
% The loop that solves the differential equation:
for i=1:n-1
f = (y(i)-2*sin(x(i)));
y(i+1) = y(i) + h * f;
end
Y_euler{k} = [x; y].';
end
syms Y(X)
eq = diff(Y) == Y - 2*sin(X);
ic = Y(0) == 1;
sol = dsolve(eq, ic);
y_sol = double(subs(sol, X, x));
hold on
plot(x, y_sol, 'r', 'DisplayName', 'true solution');
for k=1:numel(H)
plot(Y_euler{k}(:,1), Y_euler{k}(:,2), 'b--', 'DisplayName', ['Euler method h=' num2str(H(k), '%.3f')]);
end
legend
err = zeros(1,numel(H));
for k=1:numel(H)
err(k) = interp1(Y_euler{k}(:,1), Y_euler{k}(:,2), 2) - subs(sol, X, 2);
end
Comments
Leave a comment