Needing help with Newton Raphson method
이전 댓글 표시
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
Roger Stafford
2018년 2월 22일
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
답변 (1개)
Prajit T R
2018년 2월 22일
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
카테고리
도움말 센터 및 File Exchange에서 Newton-Raphson Method에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!