MATLAB: How to find a solution to (x.^2)/2-10*atan(x) using the Newton-Raphson method

methodnewtonnewton raphson

How do I find a solution to (x.^2)/2-10*atan(x) using the Newton-Raphson method? Is there a general 'body' to this method?

Best Answer

Hana, there are a couple of issues with your code. This should work:
function Xs = newtonroot(Xest)
imax = 100;
Err = 1e-10;
for i = 1:imax
Xi = Xest - (Xest^2/2-10*atan(Xest))/(Xest-10/(1+Xest^2));
if (abs(Xi - Xest) < Err)
Xs = Xi;
break
end
Xest = Xi;
end
if i == imax
fprintf('Solution was not obtained within %i iterations.\n',imax)
Xs = ('No answer');
end
end
  • In the function definition you need to return Xs (rather than x), don't forget the equal sign.
  • The loop does not get executed. First, I do not see imax defined (globally?). Second, even if it is defined i is set to imax.
  • Lastly, you probably will converge faster (and more consistenly) with abs((Xi - Xest) < Err). Just think of a scenario, where the root is close to zero, the error terms will blow up.
  • Of course, you can also pass alogrithm parameters to the function rahter than define them locally.