question 1: Use the bisection method to solve the equation $x^3-2=0$. Please code the bisection algorithm by yourself.

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
%matlab code:
%define function f
f=inline('x^3-2');

%set the tolerance
tol=1e-8;

%define the initial interval
a=1;b=2;

%define the mid point
x=(a+b)/2;

%define the max distance
d=(b-a)/2;

%get the signal of the left endpoint
s=sign(f(a));

%set the while loop
while d>tol;
%shrink the distance
d=d/2;
%check whether the midpoint is larger or not
if s==sign(f(x)) x=x+d;
else x=x-d; end

end

question 2: Use the bisection method to solve the equation $x^3-2=0$. Please apply the “bisect” function in CEtools to solve the question.

1
2
3
4
5
%matlab code:
%define function f
f=inline('x^3-2');
%apply function bisect
bisect(f,1,2)

question 3: Plot the whole iteration path in E1, using array x(i) to store the x value when the number of iteration is i

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
31
32
33
34
35
36
%matlab code:
%define the time-counter i
i=1;
%define function f
f=inline('x^3-2');

%set the tolerance
tol=1e-8;
%tol=1e-2;

%define the initial interval
a=1;b=2;

%define the mid point
x(i)=(a+b)/2;

%define the max distance
d=(b-a)/2;

%get the signal of the left endpoint
s=sign(f(a));

%set the while loop
while d>tol;
%shrink the distance
d=d/2;
%check whether the midpoint is larger or not
if s==sign(f(x(i))) x(i+1)=x(i)+d;
else x(i+1)=x(i)-d; end
%add to the time-counter
i=i+1;

end

%plot the iteration path
plot(1:i,x(1:i))

question 4: Learn how to construct and call function in MATLAB. Let function [x,gval] = myfun(g,x,maxit,tol), gval = feval(g,x); Finally, call “myfun” within the same folder, to solve the equation $x=x^{0.5}$ with initial guess 0.4, max iteration number 100, and tolerance 1e-6.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
%matlab code:
%create a new file myfun and define the function
function [x,gval] = myfun(g,x,maxit,tol)
%set the for loop
for it=1:maxit
%get the initial function value
gval = feval(g,x);
%check if the distance is small enough
if norm(gval-x)<tol return;
else x=gval; end

end

%warning
warning('this qusetion is not converged')

%main file
g=inline('x^0.5);
x=myfun(g,0.4,100,1e-6)