Spring 2020

Math 151B: Applied Numerical Methods

Discussion Section 1A

Wonjun Lee



Week3

Tuesday

About HW2.

Link to the video

Enter password:

Disucssion Section Note.

Download

Matlab code for Question 3.
% 0 <= t <= 1
a = 0;
b = 1;

% initial condition
y0 = 0;

% actual solution of y(1)
exact_y = 3/2;

% |--------------------|
% 0                    1
% N = 1
% h = 1

% |---------|----------|
% 0        1/2         1
% N = 2
% h = 1/2

% |------|------|------|
% 0      1/3    2/3    1
% N = 3
% h = 1/3

x_arr = zeros(1,10);
y_arr = zeros(1,10);

% ------- plotting Forward Euler's method --------
for jj = 1:10
    N = 2^jj;
    h = (b-a)/N;
    x_arr(jj) = h;
    y = y0;

    for i = 1:N
        t = (i-1)*h;
        y = y + h * f(t,y);
    end
    y_arr(jj) = abs(exact_y - y);
end

loglog(x_arr, y_arr)

% --------------------------

% ------- plotting Modified Euler's method --------
for jj = 1:10
    N = 2^jj;
    h = (b-a)/N;
    x_arr(jj) = h;
    y = y0;

    for i = 1:N
        t = (i-1)*h;
        y = y + h/2 * (f(t,y) + f(t+h, y+h*f(t,y)));
    end
    y_arr(jj) = abs(exact_y - y);
end

loglog(x_arr, y_arr)
legend(["Euler", "Modified Euler"])

% --------------------------

function val = f(t,y)
%     val = t^2 - 1;
%     val = 5*t^4 - 2*t^3 + 1;
    val = 2 * y/t + t^2 * cos(t);
end