function [outputs] function_name (inputs) % Name % Date % Function description %
ID: 3881280 • Letter: F
Question
function [outputs] function_name (inputs) % Name % Date % Function description %Description of inputs, including units % Description of outputs,including units % Any test cases you've used to test your code. % These are here mainly for convenience so that you don't need to remember what you % were testing from session to session. Be sure to include not only the inputs but % the expected outputs. % Input testing and default values % Main body code, properly documented end % while the final end is not required by MATLAB, % I have found that including it does help with debuggingExplanation / Answer
Solution:-
The false-position method in Matlab is as follows.
we will assume a file f.m with contents
function y = f(x)
If y = x3- 2; exists. Then:
format long
epsabs = 1e-5;
epsstep = 1e-5;
a = 0.0;
b = 2.0;
step_size = Inf;
while (step_size >= epsstep || ( abs( f(a) ) >= epsabs && abs( f(b) ) >= epsabs ) )
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
[a b]
Ans = 1.259915864579067 2
abs(f(a))
Ans = 0.0000246934256663
abs(f(b))
ans = 6
Thus, we will choose 1.259915864579067 as our approximation to the cube-root of 2, which has an actual value of 1.259921049894873.
//// Now function will be implemented like that ///////
function [ r ] = false_position( f, a, b, N, epsstep, epsabs )
% Check that that neither end-point is a root
% and if f(a) and f(b) have the same sign, throw an exception.
if ( f(a) == 0 )
r = a;
return;
elseif ( f(b) == 0 )
r = b;
return;
elseif ( f(a) * f(b) > 0 )
error( 'f(a) and f(b) do not have opposite signs' );
end
% We will iterate N times and if a root was not
% found after N iterations, an exception will be thrown.
cold = Inf;
for k = 1:N
% % Find the false position%%
c = (a*f(b) + b*f(a))/(f(b) - f(a));
% % Check if we found a root or whether or not %%
% we should continue with:
% [a, c] if f(a) and f(c) have opposite signs, or
% [c, b] if f(c) and f(b) have opposite signs.
if ( f(c) == 0 )
r = c;
return;
elseif ( f(c)*f(a) < 0 )
b = c;
else
a = c;
end
% If |b - a| < epsstep, check whether or not
% |f(a)| < |f(b)| and |f(a)| < epsabs and return 'a', or
% |f(b)| < epsabs and return 'b'.
if ( abs( c - cold ) < epsstep )
if ( abs( f(a) ) < abs( f(b) ) && abs( f(a) ) < epsabs )
r = a;
return;
elseif ( abs( f(b) ) < epsabs )
r = b;
return;
end
end
cold = c;
end
error( 'the method did not converge' );
end
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.