Needing help with Newton Raphson method

4 visualizzazioni (ultimi 30 giorni)
bhador
bhador il 8 Feb 2018
Commentato: Roger Stafford il 22 Feb 2018
So, I have attached my Newton Raphson script and I just want someone to double check if it is right or not. You might not see a f or fprime because they are in a different script. I'm required to make the output x1 an array that stores each new guess as it is generated and I'm having a hard time with that.
function [x1,err,iter] = newtonraphson(f,fprime,x0,tol,max_iter)
iter = 0; while (1)
xl = x0;
x0 = xl - f(x0)/fprime(x0);
iter = iter + 1;
if x0 ~= 0
err = abs((x0 - xl)/x0);
end
if err <= tol || iter >= max_iter
break
end
end
And then below is the driver that should use the function was created above and so display the calculated values of x1 and err for each iteration in a table formatted with fprintf. Finally, make a 1 x 3 subplot clearly showing the root-finding function and the results of each iteration. I tried everything in mind but nothing worked.
y = @(x) tanh(x.^2-9) - 3;
dy = @(x) (4.*x)./(cos(18+2.*x.^2)+1); [x1,err,iter] = newtonraphson(y,dy,3.2,0.0001,3);
Note: both scripts are written separately in two different m files. Thank you in advance
  1 Commento
Roger Stafford
Roger Stafford il 22 Feb 2018
Your derivative of tanh(x.^2-9) is incorrect. It should be:
dy = 2*x.*sech(x.^2-9).^2 = 2*x./cosh(x.^2-9).^2

Accedi per commentare.

Risposte (1)

Prajit T R
Prajit T R il 22 Feb 2018
Hi You can try this code:
function [xlist,err,iter] = newtonraphson(f,fprime,x0,tol,max_iter)
xlist=[x0];
iter = 0;
x1=x0;
while (1)
x0 = x1; %For the first iteration, it takes the value x0. For all later iterations, it takes the previous value.
x1 = x0 - f(x0)/fprime(x0); %As per formula
xlist(end+1)=x1; %Append the guessed value to the list
iter = iter + 1;
if x0 ~= 0
err = abs((x0 - xl)/x0);
end
if err <= tol || iter >= max_iter
break
end
end
end
Cheers

Community Treasure Hunt

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

Start Hunting!

Translated by