Sequence of Bisect implementations
Loading...
Searching...
No Matches
bisect_vis.m
Go to the documentation of this file.
1%%
2clear, clc, close all
3
4%% define function and intervals
5syms x
6% f(x) = sin(x) - 0.5 * x; a = 0.01; b = 2;
7% f(x) = sqrt(sin(x)) - 0.5 * x; a = 0.01; b = 2;
8f(x) = sqrt(sin(x)) - 0.5 * x^6; a = 0.01; b = 2;
9% f(x) = -atan(100*(x-1.23456789)); a = 0.1; b = 2;
10% f(x) = (1.234567-x)*(x+0.987654); a = 1; b = 2;
11
12%% define interval
13a = 0.01;
14b = 2;
15
16%% graphics
17f0=figure();
18fplot(f,[a,b]); axis ([a,b,-1,2])
19hold on
20plot([a,b],[0,0],'-r')
21
22% '$f(a,b,c)=',latex(f(a,b,c)),'$'
23title(['f(x) ',char(f)]); xlabel("x")
24legend("f(x)")
25
26%%
27fnum=matlabFunction(f);
28% Define the tolerance for the bisection method: Co-pilot
29eps = 1e-6;
30%% Call the bisection method to find the root of the function f: Co-pilot
32rootApprox = Bisect(fnum, a, b, eps, 0);
33fprintf('Equation to solve: %s = 0. \n',char(f));
34disp(['mid point: Approximate root: ', num2str(rootApprox)]);
35fprintf('mid point: root: %f after %i iterations. \n',rootApprox(end),length(rootApprox));
36%% Linear improved bisection
37%rootLinear = Bisect(fnum, a, b, eps, true);
38rootLinear = Bisect(fnum, a, b, eps, 1);
39fprintf('Equation to solve: %s = 0. \n',char(f));
40disp(['linear: Approximate root: ', num2str(rootLinear)]);
41fprintf('linear: root: %f after %i iterations. \n',rootLinear(end),length(rootLinear));
42
43%
44rootQuad = Bisect(fnum, a, b, eps, 2);
45disp(['quad: Approximate root: ', num2str(rootQuad)]);
46fprintf('quad: root: %f after %i iterations. \n',rootQuad(end),length(rootQuad));
47
48%%
49f3=figure();
50% Evaluate the function at the approximate root and plot the result
51% semilogy(rootApprox, f_val, '*b', 'MarkerSize', 10);
52semilogy(abs(rootApprox-rootApprox(end)), '-*m', 'MarkerSize', 10);
53hold on
54semilogy(max(eps/10,abs(rootLinear-rootLinear(end))), '-*b', 'MarkerSize', 10);
55semilogy(max(eps/10,abs(rootQuad-rootQuad(end))), '-or', 'MarkerSize', 10);
56
57title("Iteration history"); xlabel("iteration k"); ylabel("|x^\ast-x_k|")
58legend("midpoint", "linear", "quadratic");
59grid on;
60
61
62%%
63function xvec = Bisect(func,a,b,eps,method)
64% f(a) > = 0 >= f(b)
65% Initialize the bisection method: Co-pilot
66xvec = [];
67fc = 2*eps; % guarantee entry into the loop
68while abs(fc) >= eps && (b - a) / 2 > eps
69 if 2==method
70 Visualize_Interval_subdivision(func,a,b)
71 end
72 fa=func(a); fb=func(b);
75 if (1==method && (-fa/fb>TFAC || -fb/fa>TFAC) && length(xvec)<4) % improve linear
76 method_loc = 0;
77 fprintf('switch method to bisect at [%f, %f]\n',a,b);
78 end
79 switch method_loc
80 case 0 % midpoint
81 c = (a + b) / 2;
82 case 1 % linear
83 c = a-(b-a)*fa/(fb-fa);
84 case 2 % quadratic
85 c = (a + b) / 2;
86 dd =[1 a a^2; 1 b b^2; 1 c c^2]\[fa;fb;double(func(c))];
87 cr = getRoot(dd,a,b);
88 if ~isempty(cr)
89 c = cr(1);
90 else
91 disp("no root found")
92 end
93 otherwise
94 disp("Unknown method! Choose from [0,2]")
95 end
96 fc = func(c);
97 if abs(fc) < eps
98 % % we found the root
99 % xvec = [xvec, c]; % Exact root found
101 elseif fa * fc < 0
102 b = c; % Root is in the left half
103 else
104 a = c; % Root is in the right half
105 end
106 xvec = [xvec, c]; % Store the midpoint
107end
108end
109
110%%
111function r = getRoot(dd,a,b)
112r = roots(dd(end:-1:1));
113r = r(a<=r & r<=b);
114if length(r)==2
115 disp("!! 2 roots !!")
116end
117end
118%%
119function Visualize_Interval_subdivision(func,a,b)
120%
121fa=func(a); fb=func(b);
122
123c0 = (a + b) / 2; % midpoint
124c1 = a-(b-a)*fa/(fb-fa); % linear
125
126% c2 = c0; % quadratic via midpoint
127c2 = c1; % quadratic via linear
128dd =[1 a a^2; 1 b b^2; 1 c2 c2^2]\[fa;fb;double(func(c2))];
129cr = getRoot(dd,a,b);
130if ~isempty(cr)
131 c2 = cr(1);
132else
133 disp("no root found")
134end
135
136figure()
137plot([a,b],[fa,fb],'sg')
138hold on
139plot(c0,func(c0),'*m')
140plot(c1,func(c1),'db')
141plot(c2,func(c2),'or')
142%
143x = linspace(a,b,101);
144plot(x,func(x),'-g')
145plot([a,b],[fa,fb],'-b')
146y = polyval(dd(end:-1:1),x);
147plot(x,y,'-r')
148plot([a,b],[0,0],'-k')
149title("Visualize 3 strategies in bisection step")
150legend("given data","midpoint","linear","quadratic")
151
152end
153
154%%
155function xvec = Bisect_org(func,a,b,eps,linear)
156% Initialize the bisection method: Co-pilot
157xvec = [];
158while (b - a) / 2 > eps
159 if linear
160 midpoint = double(a-(b-a)*func(a)/(func(b)-func(a)));
161 else
162 midpoint = (a + b) / 2;
163 end
164 % if subs(func, x, midpoint) == 0
165 % if func(midpoint) == 0
166 if abs(func(midpoint)) < eps
167 xvec = [xvec, midpoint]; % Exact root found
168 break;
169 % elseif subs(func, x, a) * subs(func, x, midpoint) < 0
170 elseif func(a) * func(midpoint) < 0
171 b = midpoint; % Root is in the left half
172 else
173 a = midpoint; % Root is in the right half
174 end
175 xvec = [xvec, midpoint]; % Store the midpoint
176end
177end
double g(const double x)
Calculates function .
Definition Bisect3.cpp:29
double Bisect(const double a, const double b, const double eps)
Definition Bisect6.cpp:124
guarantee entry into the loop while abs(fc) >
dd
Definition bisect_vis.m:86
fprintf('Equation to solve:%s=0. \n', char(f))
Exact root found break
Definition bisect_vis.m:100
elseif x
Definition bisect_vis.m:169
elseif fa *fc< 0 b=c;% Root is in the left half else a=c;% Root is in the right half end xvec=[xvec, c];% Store the midpointendend%%function r=getRoot(dd, a, b) r=roots(dd(end:-1:1));r=r(a<=r &r<=b);if length(r)==2 disp("!! 2 roots !!") endend%%function Visualize_Interval_subdivision(func, a, b)%fa=func(a);fb=func(b);c0=(a+b)/2;% midpointc1=a-(b-a) *fa/(fb-fa);% linear% c2=c0;% quadratic via midpointc2=c1;% quadratic via lineardd=[1 a a^2;1 b b^2;1 c2 c2^2]\[fa;fb;double(func(c2))];cr=getRoot(dd, a, b);if ~isempty(cr) c2=cr(1);else disp("no root found") endfigure() plot([a, b], [fa, fb], 'sg') hold onplot(c0, func(c0),' *m') plot(c1, func(c1), 'db') plot(c2, func(c2), 'or')%x=linspace(a, b, 101);plot(x, func(x),'-g') plot([a, b], [fa, fb],'-b') y=polyval(dd(end:-1:1), x);plot(x, y,'-r') plot([a, b], [0, 0],'-k') title("Visualize 3 strategies in bisection step") legend("given data","midpoint","linear","quadratic") end%%function xvec=Bisect_org(func, a, b, eps, linear)% Initialize the bisection method:Co-pilotxvec=[];while(b - a)/2 > eps if linear midpoint
Definition bisect_vis.m:160
cr
Definition bisect_vis.m:87
graphics f0
Definition bisect_vis.m:17
disp(['mid point:Approximate root:', num2str(rootApprox)])
ylabel("|x^\ast-x_k|") legend("midpoint"
clc
Definition bisect_vis.m:2
axis([a, b,-1, 2]) hold on plot([a
linear
Definition bisect_vis.m:58
Call the bisection method to find the root of the function eps
Definition bisect_vis.m:31
end switch method_loc case midpoint c
Definition bisect_vis.m:81
if(1==method &&(-fa/fb >TFAC||-fb/fa >TFAC) &&length(xvec)< 4) % improve linear method_loc=0
Define the tolerance for the bisection method
Definition bisect_vis.m:29
a
Definition bisect_vis.m:6
f3
Definition bisect_vis.m:49
Call the bisection method to find the root of the function false
Definition bisect_vis.m:31
fc
Definition bisect_vis.m:67
rootQuad
Definition bisect_vis.m:44
rootApprox
Definition bisect_vis.m:32
Evaluate the function at the approximate root and plot the result semilogy(rootApprox, f_val, ' *b', 'MarkerSize', 10)
quadratic
Definition bisect_vis.m:58
fplot(f,[a, b])
TFAC
Definition bisect_vis.m:74
b
Definition bisect_vis.m:6
method_loc
Definition bisect_vis.m:73
title("Iteration history")
end if subs(func, x, midpoint)
xlabel("x") legend("f(x)") %% fnum
Call the bisection method to find the root of the function f
Definition bisect_vis.m:31
function xvec
Definition bisect_vis.m:63
grid on
Definition bisect_vis.m:59
Linear improved bisection rootLinear
Definition bisect_vis.m:37
fb
Definition bisect_vis.m:72
clear
Definition bisect_vis.m:2