zer0kai
zer0kai

Reputation: 259

Newton method implementation in matlab

I wanted to implement the newton method. My code is so far:

f is a function-handle, df the differentiate f (also a function-handle) and x is the start value.

It works for some functions, but for example when I ask for

newton(@(x) x^2,@(x) 2*x,1)

it comes in an infinite loop. How to fix this?

Upvotes: 0

Views: 214

Answers (1)

K. A. Buhr
K. A. Buhr

Reputation: 51119

The usual check for termination for Newton's method is to see if the result of another iteration is "very close" to the previous answer, but you're using the check:

if abs(xn) == abs(x)

which basically requires the two values to be identical (except you've used abs, which is a bug since it would accept an answer that's so wrong that an iteration flips the sign). For some problems, this might work, but this is very likely to lead to an infinite loop with the iterations cycling through a set of very close values.

Change your termination test to:

if abs(xn-x) < 0.0000001    (or something else very small)

which tests to see if xn and x differ by no more than the very small value given, and that should work.

Upvotes: 1

Related Questions