2017-05-11 4 views
0

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?

Antwort

0

Das Problem ist, wie Sie erwähnt haben. x_old wird immer auf 0 gesetzt, wenn es tatsächlich für jede Iteration auf x_i-2 gesetzt werden soll. Dies ist der entsprechende Code, den Sie ändern müssen

i = 0; % initialise iterate counter 
%Store the initial values in a different variable 
x_0 = x0; 
x_1 = x1; 
while abs(x - x_old) > tol && i < maxiters 
    x = x_1 - f(x_1) * (x_1 - x_0)/(f(x_1) - f(x_0)); % compute the new x 
    % Update the previous values 
    x_0 = x_1; 
    x_1 = x; 
    i = i + 1; % increase our counter by one 
end