Regula-falsi Method that keeps running
5 views (last 30 days)
Show older comments
I have this script for Regula-Falsi Method to get a root of a function but it just keeps running. Anyone can help find what's wrong?
f = @(x) 2.^x - x.^2 - 2; % Function whose roots are desired
xL = 4; xU = 5; % Initial guesses
Tol = 1e-6; % Tolerance (0.000001)
c = 0; % Counter for the no. of iterations
while abs( xU-xL ) > Tol
c = c + 1
xm = xU-f(xU)* (xU-xL)/f(xU)- f(xL); % Compute xm
fm = f(xm); % Evaluate the function at x = xm
% % Print the intermediate results
fprintf('Iteration: %d\t',c);
fprintf ('[xL,xU,xm ] = [%.6f, %.6f, %.6f]\n', xL,xU,xm);
if f(xL ) *fm < 0 % If the root is on the left,
xU = xm ; % then set xm as the new xU.
elseif fm * f( xU ) < 0 % But if the root is on the
xL = xm ; % then set xm as the new xL.
else
break; % Stop! xm is exactly the root
end
end
plot(xm,f(xm),'r*', 'Markersize', 10); % plot the xm points
fprintf ('The root is: %.6f \n', xm);
0 Comments
Accepted Answer
Alan Stevens
on 19 Mar 2023
Brackets!!
f = @(x) 2.^x - x.^2 - 2; % Function whose roots are desired
xL = 4; xU = 5; % Initial guesses
Tol = 1e-6; % Tolerance (0.000001)
c = 0; % Counter for the no. of iterations
while abs( xU-xL ) > Tol
c = c + 1;
xm = xU-f(xU)* (xU-xL)/(f(xU)- f(xL)); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Put brackets round f(xU)-f(xL)
fm = f(xm); % Evaluate the function at x = xm
% % Print the intermediate results
fprintf('Iteration: %d\t',c);
fprintf ('[xL,xU,xm ] = [%.6f, %.6f, %.6f]\n', xL,xU,xm);
if f(xL ) *fm < 0 % If the root is on the left,
xU = xm ; % then set xm as the new xU.
elseif fm * f( xU ) < 0 % But if the root is on the
xL = xm ; % then set xm as the new xL.
else
break; % Stop! xm is exactly the root
end
end
plot(xm,f(xm),'r*', 'Markersize', 10); % plot the xm points
fprintf ('The root is: %.6f \n', xm);
More Answers (0)
See Also
Categories
Find more on Multidimensional Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!