Regula-falsi Method that keeps running
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Alan Stevens
2023-3-19
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);
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Dialog Boxes 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!