Lab12
Lab12
Lab-12
Euler’s method
Name:
Sobia Karim
Roll Number:
2022-BSE-069
Semester:
V–B
EULER’S METHOD
Code with function:
clc; clear; close all;
% Define the differential equation dy/dx = f(x, y)
f = @(x, y) x + y; % Example: dy/dx = x + y
% Inputs
x0 = 0; % Initial x-value
y0 = 1; % Initial y-value
h = 0.1; % Step size
x_end = 2; % Final x-value
% Initialization
x = x0:h:x_end; % Create x values
n = length(x); % Number of steps
y = zeros(1, n); % Preallocate y array
y(1) = y0; % Initial condition
% Euler's Method Loop
for i = 1:n-1
y(i+1) = y(i) + h * f(x(i), y(i)); % Update y using Euler's formula
end
% Display Results
disp('x values:');
disp(x);
disp('y values:');
disp(y);
figure;
plot(x, y, '-o', 'LineWidth', 1.5);
title('Euler''s Method Solution');
xlabel('x');
ylabel('y');
grid on;
legend('Euler''s Approximation');
Figure:
Without Function:
Code:
clc; clear; close all;
x0 = 0;
y0 = 1;
h = 0.1;
x_end = 2;
x = x0:h:x_end;
n = length(x);
y = zeros(1, n);
y(1) = y0;
for i = 1:n-1
dydx = x(i) + y(i);
y(i+1) = y(i) + h * dydx;
end
disp('x values:');
disp(x);
disp('y values:');
disp(y);
figure;
plot(x, y, '-o', 'LineWidth', 1.5);
title('Euler''s Method Solution');
xlabel('x');
ylabel('y');
grid on;
legend('Euler''s Approximation');
Pseudocode: