Ich habe mich schon eine Weile mit dieser Funktion herumgeschlagen und ich finde keinen Weg, das Problem zu lösen, das ich habe.Probleme mit der Sekantenwurzel-Suchfunktion in MATLAB
Mein Code ist:
function [x,i] = secant(f, x0, x1, tol, maxiters)
%SECANT Secant method
% [X,I] = SECANT(F, X0, X1, TOL, MAXITERS) performs the secant
% method with F(x), starting at x_0 = X0 and x_1 = X1, and continuing
% until either |X_i+1 - X_i| <= TOL, or MAXITERS iterations have
% been taken. The number of iterations, I, is also returned.
% An error is raised if the first input is not a function handle.
% A warning is raised if the maximum number of iterations is reached
% without achieving the tolerance.
if ~isa(f, 'function_handle')
error('Your first input was not a function handle')
end
i = 0; % initialise iterate counter
x = x1;
x_old = x0;
while abs(x - x_old) > tol && i < maxiters
x_old = x0;
x = x - f(x)*(x - x_old)/(f(x) - f(x_old)); % compute the new x
i = i + 1; % increase our counter by one
end
if abs(x - x_old) > tol
warning('Maximum number of iterations reached without achieving tolerance.')
end
Wenn ich den Code ausführen ich nicht die gleiche Antwort bekommen, wie ich mit der Hand tun. Derzeit verwende ich,
f = @(x) 0.9cos(x) - sqrt(x)
x0 = 0
x1 = 1
tol = 1e-08
maxiters = 4
Ich glaube, dass meine Probleme von der Leitung x_old = x0;
kommen, die unter while abs(x - x_old) > tol && i < maxiters
.Ich denke, ist es, jedes Mal, wenn ich die Funktion aufrufen, setzt es x
zurück zu x0
.
Wie kann ich das umgehen?