Not able to figure out error in code for Newton Raphson Method

186 Views Asked by At

I'm trying to write a MATLAB function to solve an equation by Newton Raphson Method but the answer it is showing is zero, which is not correct. I'm not able to figure out the mistake in the code. Please help.

function x = newton(x0)
tolerance = 10^(-8);
error = 999;
x = x0;
while error>tolerance
f = x-x^(1/3)-2; % Function value
dfdx = 1-(1/3)*x^(-2/3); % Derivative value
x = x-f/dfdx; % Newton-Raph Equation
error = abs(((x-x0)/x)*100);
x0 = x;
end
end
3

There are 3 best solutions below

1
On BEST ANSWER

Newton's method is not globally convergent. Provide your function with an appropriate seed and it will converge. I ran your code with a seed of 5 and it works fine, converging to approximately 3.5214. Note that you have an extra "end" statement in your code.

2
On

At first glance your method looks appropriate. I would suggest using "format long" to ensure you are viewing more decimal places. If in standard mode your tolerance is so small it might just come out as zero.

1
On

Give a display command at the end of the loop , so that it gives you the result after every iteration. You can debug on your own then.