How to write a code for Newton Raphson method

1 view (last 30 days)
Ashley Warnes
Ashley Warnes on 11 Feb 2017
Edited: Jan on 11 Feb 2017
I need to write a code to solve newton raphson method to 4dp. Using the function f(x)=x^3-2*x+2 and starting value x=-1.5, I've got the code below but can't seem to solve it as x(n) turns into an array rather than just the value of x.
x(1)=-1.5;
n=2;
while abs(x^3-2*x+2)>0.0001
x(n)=x(n-1)+((((x(n-1))^3)-2*(x(n-1))+2)/(3*((x(n-1))^2)-2));
n=n+1;
end
x

Answers (1)

Jan
Jan on 11 Feb 2017
Edited: Jan on 11 Feb 2017
A vectors looks nice as output. All you have to change is, that you check the last element for the while condition only:
while abs(x(end)^3 - 2 * x(end) + 2) > 0.0001
But the obtained sequence does not converge. It seems like there is a bug in the Newton-Raphson formula, a + instead of a - .
Avoid an infinite loop by setting a maximum iteration count, e.g.:
if n > 1e6
error('Sequence does not converge');
end

Community Treasure Hunt

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

Start Hunting!