Set Element Index to 1

3 Ansichten (letzte 30 Tage)
Julia
Julia am 9 Jun. 2023
Bearbeitet: John D'Errico am 9 Jun. 2023
Hello I am getting an error on my code for the line dfval = (f(x(i))-f(x(i-1)))/(x(i)-x(i-1)), I know this is because I am trying to access the 0th element in my x vector but I'm not sure how to set the first elements index to one. Can anyone help with this?
Thanks!
function[x, conv, res, i] = ...
newton_raphson_func(f, df, guess1, conv_tol, res_tol, max_iter)
% Initial Guess
x(1) = guess1;
% Initial Convergence
conv(1) = 0 ;
% Initial Residual
res(1) = abs(f(x(1)));
fprintf(' Iteration x Residual Convergence');
fprintf('=========== ===== ========== =============');
fprintf(' %2i %.8e %.4e %.4e\n', 0,x(1),res(1),conv(1));
% Initialize the Iteration Counter
i = 1;
% Iterate Using our Formula
while i<max_iter
fval = f(x(i));
dfval = (f(x(i))-f(x(i-1)))/(x(i)-x(i-1));
if (dfval==0) || (isnan(dfval))
error("!!! FAILED. The derivative value is %i. Try another guess.", dfval)
break;
end
x(i+1) = x(i) - ((fval)/(dfval));
conv(i+1) = abs(x(i+1)-x(i));
res(i+1) = abs(f(x(i+1)));
fprintf(' %i %.8e %.4e %4e',i,x(i+1),res(i+1),conv(i+1))
if res(i+1)<res_tol && conv(i+1)<conv_tol
break;
end
i = i + 1;
end

Antworten (1)

John D'Errico
John D'Errico am 9 Jun. 2023
Bearbeitet: John D'Errico am 9 Jun. 2023
Your real problem is you misunderstand what you are doing, in wanting to write a Newton-Raphson code! If I had to guess, your code uses an old homework solution, and you were hoping to just re-use that code.
The code you have written is an implementation of the SECANT METHOD. What is the difference? The two are actually closely related, sort of.
You have written
dfval = (f(x(i))-f(x(i-1)))/(x(i)-x(i-1));
Essentially, you are taking the last TWO points, and finding the slope between the two. Then you extrapolate that line down to zero. And what is that method called? THE SECANT METHOD!!!!!
So now how is that different from Newton-Raphson? NR has you find the slope of the function AT THAT POINT. It then extrapolates the tangent line, based on that slope, down to zero.
Do you see the difference? If you don't, then you will not understand how to implement Newton-Raphson. As a hint, how might you compute a numerical approximation to the derivative? Consider this modification:
dx = 1e-8;
dfval = (f(x(i) + dx)-f(x(i)))/dx;
Do you see this just computes the slope at the point f(x(i))? It uses a simple finite difference approximation to compute that slope. But that approximation is just how you learned to compute a derivative. (I hope.) There is no need to use the last TWO points, as you would with the secant method.

Kategorien

Mehr zu Spline Postprocessing finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by