Regula-falsi Method that keeps running
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
BG
el 19 de Mzo. de 2023
Comentada: BG
el 19 de Mzo. de 2023
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 comentarios
Respuesta aceptada
Alan Stevens
el 19 de Mzo. de 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);
Más respuestas (0)
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!