Solution for Ex 1. Write the following functions.
1
function [x,iter] = bisection(f,a,b,tol,maxiter)2
%BISECTION for finding zeros of functions3
res = tol+1; iter = 0; % Initialize4
while res > tol && iter < maxiter5
c = (a+b)/2;6
if f(c) == 07
x = c; break;8
elseif f(c)*f(a) < 09
b = c;10
elseif f(c)*f(b) < 011
a = c;12
end13
res = abs(f(c)); iter = iter+1;14
end15
x = c;16
if iter >= maxiter17
disp('no convergence iter > maxiter')18
end1
function [x,iter] = newton(f,fp,x0,tol,maxiter)2
%NEWTON for finding zeros of functions3
res = tol+1; iter = 0; % Initialize4
while res > tol && iter < maxiter5
x0 = x0−
f(x0)/fp(x0);6
res = abs(f(x0)); iter = iter+1;7
end8
x = x0;9
if iter >= maxiter10
disp('no convergence iter > maxiter')11
end1
Solution for Ex 2. On the script named Esercizio2 write the following code.
1
clear all2
close all3
clc4
format long5
f = @(x) exp(x)−
4*x.^2;6
x = linspace(−
2,5);7
figure8
hold on9
grid on10
plot(x,f(x))-2 -1 0 1 2 3 4 5
-20 -10 0 10 20 30 40 50
1
fp = @(x) exp(x)−
8*x;2
x1 = bisection(f,−
1,0,1.e−
06,50)3
x2 = newton(f,fp,1,1.e−
06,50)4
x1 =−
0.4077768325805665
x2 = 0.7148059123645802