Chapter3 Prob20
Chapter3 Prob20
3.20 Write a MATLAB user-defined function that solves a nonlinear equation f ( x ) = 0 with the regula
falsi method. Name the function Xs = RegulaRoot(Fun,a,b,ErrMax), where the output argument
Xs is the solution. The input argument Fun is a name for the function that calculates f ( x ) for a given x (it
is a dummy name for the function that is imported into RegulaRoot), a and b are two points that bracket
the root, and ErrMax the maximum error according to Eq. (3.9).
The program should include the following features:
• Check if points a and b are on opposite sides of the solution. If not, the program should stop and dis-
play an error message.
• The number of iterations should be limited to 100 (to avoid an infinite loop). If a solution with the
required accuracy is not obtained in 100 iterations, the program should stop and display an error mes-
sage.
Use the function RegulaRoot to solve the equation in Problem 3.3 (use a = 0.1 , b = 1.4 ).
Solution
function Xs = RegulaRoot(Fun,a,b,ErrMax)
% RegulaRoot finds the root of Fun = 0 using the regula falsi method.
% Input variables:
% Fun Name for the function (imported as a handle) that calculates Fun for a
given x.
% a, b Two points that bracket the root.
% TolMax The maximum error.
% Output variable:
% Xs Solution
imax = 100;
Fa = Fun(a);
Fb = Fun(b);
% Checks if points a and b are on opposite sides of the solution.
if Fa*Fb > 0
Xs = ('Error: The function has the same sign at points a and b.');
else
for i = 1:imax
if i >1
XsIminus1 = Xs;
end
Excerpts from this work may be reproduced by instructors for distribution on a not-for-profit basis
for testing or instructional purposes only to students enrolled in courses for which the textbook
has been adopted. Any other reproduction or translation of this work beyond that permitted by
Sections 107 or 108 of the 1976 United States Copyright Act without the permission of the
copyright owner is unlawful.
2
Xs = (a*Fb-b*Fa)/(Fb-Fa);
FXs=Fun(Xs);
if FXs == 0
break
end
% Ckecks if the estimated relative error is smaller than ErrMax.
if i >1 & abs((Xs-XsIminus1)/XsIminus1) <= ErrMax
break
end
if i == imax
fprintf('Solution was not obtained in %i iterations',imax)
break
end
if Fa*FXs < 0
b = Xs;
Fb = FXs;
else
a = Xs;
Fa = FXs;
end
end
end
Excerpts from this work may be reproduced by instructors for distribution on a not-for-profit basis
for testing or instructional purposes only to students enrolled in courses for which the textbook
has been adopted. Any other reproduction or translation of this work beyond that permitted by
Sections 107 or 108 of the 1976 United States Copyright Act without the permission of the
copyright owner is unlawful.