For this assignment we will be writing the following MATLAB functions. bisect m
ID: 3818465 • Letter: F
Question
For this assignment we will be writing the following MATLAB functions. bisect m false-pos m nroot.m bisect0, false-pos() Both bisect() and false-pos() will use the following structure. 1. Initialize variables. 2. Update the bracket. The update for bisect() should use incsearch0, and the update for false.pos should use the formula derived in class (or from the text.) 3. Repeat the above step until the relative error between the endpoints is smaller than 10 12 or until the iteration count reaches 1000. Use a for loop for bisect0 and a while loop for false.pos0. Both functions will accept three arguments. The first argument is the anony- mous function of the function we're finding the root of. The second and third arguments are the lower and upper bounds of the bracket respectively. For example, if we wish to find the root of sin(r) over the interval (2.5, 3.5) we could use the following function calls bisect (a (x) sin (x), 2.5 3.5) f @(x) sin (x) false-pos (f 2.5 3.5Explanation / Answer
CODE -
bisect.m
function [x e] = bisect(f,a,b)
% Inputs: f -- an inline function
% a,b -- left and right edges of the interval
% Outputs: x -- the estimated solution of f(x) = 0
% e -- an upper bound on the error
format long
c = f(a); d = f(b);
if c*d > 0.0
error('Function has same sign at both endpoints.')
end
eps_abs = 1e-5;
eps_step = 1e-5;
disp(' x y')
%for i = 1:n
while (b - a >= eps_step || ( abs( f(a) ) >= eps_abs && abs( f(b) ) >= eps_abs ) )
x = (a + b)/2;
y = f(x);
disp([ x y])
if y == 0.0 % solved the equation exactly
e = 0;
break % jumps out of the for loop
end
if c*y < 0
b=x;
else
a=x;
end
end
e = (b-a)/2;
Output:
>> res = bisect(@(x) sin(x),2.5,3.5)
res =
3.141593933105469
------------------------------------------------------------------------
CODE - false_pos.m
function [a b] = false_pos(f,a,b)
% Inputs: f -- an inline function
% a,b -- left and right edges of the interval
% Outputs: x -- the estimated solution of f(x) = 0
% e -- an upper bound on the error
format long
eps_abs = 1e-5;
eps_step = 1e-5;
step_size = Inf;
while (step_size >= eps_step || ( abs( f(a) ) >= eps_abs && abs( f(b) ) >= eps_abs ) )
c = (f(a)*b - f(b)*a)/(f(a) - f(b));
if ( f(c) == 0 )
break;
elseif ( f(a)*f(c) < 0 )
step_size = b - c;
b = c;
else
step_size = c - a;
a = c;
end
end
Output:
>> res = false_pos(@(x) sin(x),2.5,3.5)
res =
3.141592653589793
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.