numerical analysis 0914
question 1: compute a local maximum of $f(x)=xcos(x^2)-1$ on $[0,3]$, using the function golden in CEtools. And plot the $f(x)$.

1
2
3
4
5
6
7
8
9
10
11
12
%matlab code:
%define the function f
f=inline('x*cos(x^2)-1');

%search for the maximum
x=golden(f,0,3);

%plot the figure
fplot(@(x)x*cos(x^2)-1,[0,3]);

%to plot the figure, we can also define f in the form of vector, using relevant tools for matrix
%f=inline('x.*cos(x.^2)-1');

question 2: Write your own golden section algorithm to solve the Q1

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

%set the initial interval
a=0; b=3;

%set the discount parameters
alpha1=(3-sqrt(5))/2; alpha2=(sqrt(5)-1)/2; tol=1e-8;

%get the initial two mid-points
x1=a+alpha1*(b-a);x2=a+alpha2*(b-a);

%get the function value of x1 and x2
f1=f(x1);f2=f(x2);

%define the difference
d=x2-x1;

%set the while loop
while d>tol d=d*alpha2;

%choose the interval which contains the maximum
if f2<f1 x2=x1; x1=x1-d; f2=f1; f1=f(x1);
else x1=x2; x2=x2+d; f1=f2; f2=f(x2); end

end

%choose the x which has a larger value as the final solution
if f1>f2 x=x1;
else x=x2;

end

question 3: Write your own function that implements the golden section algorithm in golden_E3.m

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
%matlab code:
%define the function golden_E3
function [x]=golden_E3(f,a,b,tol)

%set the discount parameters
alpha1=(3-sqrt(5))/2; alpha2=(sqrt(5)-1)/2;

%get the initial two mid-points
x1=a+alpha1*(b-a);x2=a+alpha2*(b-a);

%get the function value of x1 and x2
f1=f(x1);f2=f(x2);

%define the difference
d=x2-x1;

%set the while loop
while d>tol d=d*alpha2;
%choose the interval which contains the maximum
if f2<f1 x2=x1; x1=x1-d; f2=f1; f1=f(x1);
else x1=x2; x2=x2+d; f1=f2; f2=f(x2); end

end

%choose the x which has a larger value as the final solution
if f1>f2 x=x1;
else x=x2;

end

%this end is for "function"end
%main file
f=inline('x*cos(x^2)-1');
x=golden_E3(f,0,3,1e-8);