Solution for Ex 1.
The aim is the one of studying the speed of convergence of the methods. In practice we need to compare the number of iterations needed by each algorithm to reach the solution up to the desired tolerance. Note that g
2(x) = g
1(g
1(x)) . Thus, the rst iterative method gives
x
k= g
1(x
k−1) = g
(k)1(x
0), while the second one ˜x
k= g
2(˜ x
k−1) = g
2(k)(˜ x
0).
If we take ˜x
0= x
0, we obtain
˜
x
k= g
(k)2(˜ x
0) = g
(2k)1(˜ x
0).
This means that the second algorithm will converge to the solu- tion in about half of the iteration needed by the rst scheme. Write the script Esercizio1 as follows.
1
close all2
clear all3
clc4
format long5
c = 2;6
g1 = @(x) x−
(x.^2−
c)./(2*x);7
g2 = @(x) g1(g1(x));8
[x1 iter1] = fixedpoint(g1,1,1.e−
06,50)9
[x2 iter2] = fixedpoint(g2,1,1.e−
06,50)10
x1 =11
1.41421356237309512
iter1 =13
5 Solution for Ex 2. First verify (on paper) that the xed point it- eration and newton methods converge. Then, write on Esercizio2 the following code.
1
clear all2
close all3
clc4
f = @(x) x.^2−
log(x.^2+2);5
g = @(x)sqrt(log(x.^2+2));6
fp = @(x) 2*x−
2*x./(x.^2+2);7
x0 = 2; tol = 1.e−
10; nmax = 100;8
sol = fzero(f,1);9
[x,t] = bisection(f,0,2,tol,nmax);10
for i=1:t11
x_bs(i)=bisection(f,0,2,tol,i);12
x_fp(i)=fixedpoint(g,x0,tol,i);13
x_nt(i)=newton(f,fp,x0,tol,i);14
x_ai(i)=aitken(g,x0,tol,i);15
err_bs(i)=abs(x_bs(i)−
sol);16
err_fp(i)=abs(x_fp(i)−
sol);17
err_nt(i)=abs(x_nt(i)−
sol);18
err_ai(i)=abs(x_ai(i)−
sol);19
end20
figure(1), semilogy(1:t,err_bs,'−
b*',1:t,err_fp,...21
'−
go',1:t,err_nt,'−
k.', 1:t,err_ai,'−
ro'),...22
legend('Bisection','Fixed point method','Newton',...23
'Aitken''s method');24
xlabel('Number of iterations'), ylabel('Error');The results are displayed in the next page.
0 5 10 15 20 25 30 35 Number of iterations
10-20 10-15 10-10 10-5 100
Error
Bisection
Fixed point method Newton
Aitken's method
Solution for Ex 3. On a script Esercizio3 write 1
clear all2
close all3
clc4
f =@(x) tan(x)−
log(x.^2+2);5
g=@(x) atan(log(x.^2+2));6
x0=1; tol=1.e−
10; nmax=90;7
sol=fzero(f,1);8
[x,t]=fixedpoint(g,x0,tol,nmax);9
for i=1:t10
x_fp(i)=fixedpoint(g,x0,tol,i);11
x_ai(i)=aitken(g,x0,tol,i);12
err_fp(i)=abs(x_fp(i)−
sol);13
err_ai(i)=abs(x_ai(i)−
sol);14
end15
for i =1:length(err_ai)16
if err_ai(i)==017
err_ai(i) = 1.e−
16; % only for the plot18
end19
end20
figure(1), semilogy(1:t,err_fp,...21
'−
go', 1:t,err_ai,'−
ro'),...22
legend('Fixed point method',...23
'Aitken''s method');24
xlabel('Number of iterations'), ylabel('Error');The results are displayed in the next page.
0 2 4 6 8 10 12 14 16 18 20 Number of iterations
10-20 10-15 10-10 10-5 100
Error
Fixed point method Aitken's method