Grace
Grace

Reputation: 7

Newton's iteration for root finding

I am writing a function which implements Newton's iteration for root-finding on a scalar function, i.e., find x such that f(x)=0, and x_(n+1) = x_n - [f(x_n)/f'(x_n)].

f1 and f1prime are the handles to compute f and f', and x0 is an initial root estimate, and 'tol' is the toleratnce. I have to continue the iteration until either |f(x_n+1)| is less than tol or I have exceeded 10^5 iterations. And, the output of the function is x_n+1. Also... f(x)=3x^4-5x^3-12x^2 where f'(x)=12x^3-15x^2-24x.

My current code is...

f1=@(x) 3*x^4 -5*x^3 - 12*x^2;
f1prime=@(x) 12*x^3-15*x^2-24*x;
n=0;
root=x0;
    while abs(f1(x(n+1))<tol ||n>10^5
    x(n+1)=x(n)-f1(x(n))/fprime(x(n));
    n=n+1;
end 

My code should pass this test suite, but it did not. What is the problem of the above code?

tol=1e-6;
f1=@(x) 3*x^4 -5*x^3 - 12*x^2;
f1prime=@(x) 12*x^3-15*x^2-24*x;
x0=-1;
root_correct = [-1.333333];
[root]=newtonRoot(f1,f1prime,x0,tol);
tol1=1e-4;
assert( abs(root-root_correct) < tol1 , ...
 [ '\nYour output \n root = [' sprintf(' %d ',root) ']\n'   ...
   'Expected output \n root = [' sprintf(' %d ',root_correct) ']\n'   ], ...
   root,root_correct);

Upvotes: 0

Views: 443

Answers (1)

Thilo
Thilo

Reputation: 9157

Your looping condition is not correct:

while abs(f1(x(n+1)) < tol || n>10^5

continues as long as the absolute value of f1 is less than tol and n is greater than 10^5. Both conditions are not valid in the first iteration, thus you do not even iterate Newtons method once.

Try:

while abs(f1(x(n+1)) > tol && n < 10^5

Upvotes: 1

Related Questions