-
Solve the following problem using the forward Eulerโs method with stepsizes of h = 0.2 and 0.1 using Matlab programs. Compute the error and relative error using the true solution . For selected values of , observe the ratio by which the error decreases when is halved. Plot the numerical solution and true solution on the same figure for each step size.
The true solution is
Solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27clear
clc
h = 0.2;
x = 0:h:10;
f = (1 + (x.^2) / 2) .* exp(-1 .* x);
df = x .* exp(-1 .* x) - (1 + (x.^2) / 2) .* exp(-1 .* x);
df_fd(1) = NaN;
for i = 2:length(x)
df_fd(i) = (f(i) - f(i - 1)) / h;
end
plot(x, df, 'r', x, df_fd, 'bo');
hold on
h = 0.1;
x = 0:h:10;
f = (1 + (x.^2) / 2) .* exp(-1 .* x);
df = x .* exp(-1 .* x) - (1 + (x.^2) / 2) .* exp(-1 .* x);
df_fd(1) = NaN;
for i = 2:length(x)
df_fd(i) = (f(i) - f(i - 1)) / h;
end
plot(x, df_fd, 'k*'); -
Use the backward Eulerโs method to solve the following problem: Consider the linear equation
The true solution is . Solve this problem with several values of and , for . Plot the numerical solution and true solution on the same figure for each stepsize and comment on the results.
(a)Solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31clear
clc
lamada = -1;
h = 0.25;
x = 0:h:10;
df = lamada .* (sin(x) + cos(x)) + (1 - lamada) .* cos(x) - (1 + lamada) .* sin(x);
f = sin(x) + cos(x);
df_fd(length(x)) = NaN;
for i = 1:length(x) - 1
df_fd(i) = (f(i + 1) - f(i)) / h;
end
plot(x, df, 'r', x, df_fd, 'bo');
hold on
h = 0.125;
x = 0:h:10;
df = lamada .* (sin(x) + cos(x)) + (1 - lamada) .* cos(x) - (1 + lamada) .* sin(x);
f = sin(x) + cos(x);
df_fd(length(x)) = NaN;
for i = 1:length(x) - 1
df_fd(i) = (f(i + 1) - f(i)) / h;
end
plot(x, df_fd, 'k*');(b)
Solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31clear
clc
lamada = 1;
h = 0.25;
x = 0:h:10;
df = lamada .* (sin(x) + cos(x)) + (1 - lamada) .* cos(x) - (1 + lamada) .* sin(x);
f = sin(x) + cos(x);
df_fd(length(x)) = NaN;
for i = 1:length(x) - 1
df_fd(i) = (f(i + 1) - f(i)) / h;
end
plot(x, df, 'r', x, df_fd, 'bo');
hold on
h = 0.125;
x = 0:h:10;
df = lamada .* (sin(x) + cos(x)) + (1 - lamada) .* cos(x) - (1 + lamada) .* sin(x);
f = sin(x) + cos(x);
df_fd(length(x)) = NaN;
for i = 1:length(x) - 1
df_fd(i) = (f(i + 1) - f(i)) / h;
end
plot(x, df_fd, 'k*');