Alternative Newton-Method using for-loop
7 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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?
0 Kommentare
Akzeptierte Antwort
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)
Weitere Antworten (1)
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
0 Kommentare
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!