Alternative Newton-Method using for-loop

7 Ansichten (letzte 30 Tage)
Dasneves
Dasneves am 9 Dez. 2020
Kommentiert: Dasneves am 9 Dez. 2020
I have a task that requires me to create an alternative Newton-Raphson Method - not using a derivative function - described by:
where the delta value is given and its very close to 0. The input data should be a function f, the initial approach x0, the required minimum accuracy TolX for the stop criterion | (xk+1 —xk) / xk+1 | and the maximum number of iterations MaxIter. The results should be the approximation of the root z, the value of the function in the root fz and a vector containing iter iterations.
This is the code I have so far:
function [z, fz, iter] = quasinewton(f, x0, TolX, MaxIter)
% f = x^3-x^2-x+1 TolX = 1e-2
delta = 1*10^(-5);
iter = zeros(MaxIter+1,1); %Pre-allocates memory for iter vector
iter(1) = x0; %x0 = -0.2
for k = 1:MaxIter
fz = feval(f, iter(k));
dfdx = fz / (feval(f, iter(k) + delta) - fz);
iter(k+1) = iter(k) - (dfdx * delta); %Calculates new iteration
err = (iter(k+1)-iter(k))/iter(k+1); %calculates the error of sucessive iterations
fz = feval(f, iter(k+1));
if abs(err) < TolX, break; end
end
z = iter(k+1);
if k == MaxIter
fprintf('The best in %d iterations\n', MaxIter)
end
It keeps giving me the wrong iterations and instead of converging to 0 it increases iteration after iteration. I really don't understand what could be wrong. I'm new in Matlab. Any suggestions?

Akzeptierte Antwort

Alan Stevens
Alan Stevens am 9 Dez. 2020
It works for me ok using the function f = x^3-x^2-x+1 and initial guess x0 = -2. However, replace
if k == MaxIter
fprintf('The best in %d iterations\n', MaxIter)
end
by
fprintf('The best in %d iterations is f = %f at x = %f \n', k, f(z), z)
  1 Kommentar
Dasneves
Dasneves am 9 Dez. 2020
Thank you very much for dedicating a little bit of your time to respond me. I have now detected what I was doing wrong when running the function in the command window. I've also done what you suggested. :)

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Alan Stevens
Alan Stevens am 9 Dez. 2020
This
f = @(x) x^3-x^2-x+1;
MaxIter = 100;
TolX = 1e-2;
x0 = -0.2;
delta = 1*10^(-5);
iter = zeros(MaxIter+1,1); %Pre-allocates memory for iter vector
iter(1) = x0; %x0 = -0.2
for k = 1:MaxIter
fz = feval(f, iter(k));
dfdx = fz / (feval(f, iter(k) + delta) - fz);
iter(k+1) = iter(k) - (dfdx * delta); %Calculates new iteration
err = (iter(k+1)-iter(k))/iter(k+1); %calculates the error of sucessive iterations
fz = feval(f, iter(k+1));
if abs(err) < TolX, break; end
end
z = iter(k+1);
fprintf('The best in %d iterations is f = %f at x = %f \n', k, f(z), z)
results in
The best in 9 iterations is f = 0.000102 at x = 1.007135

Kategorien

Mehr zu App Building finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by