Regula-falsi Method that keeps running
조회 수: 9 (최근 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에서 Instrument Control Toolbox에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
