Help with Newton's Root Method Code
23 views (last 30 days)
Show older comments
Jose Trevino on 22 Feb 2016
Hi, I made this code to calculate the roots of a function. However, it works with some functions and with others it doesn't. The user is supposed to input the function (f), the derivate (df) an initial guess (x0) the tolerance (tol) and the number of iterations(N). I managed to convert a pseudocode to this code but I am stuck. Theoretically it should be able to calculate the root of any function. A little help would be great The code is this
function [ r, resarray ] = newton( f, df, x0, tol, N )
f = inline(f);
df = inline(df);
r(1) = x0 - (f(x0)/df(x0));
resarray(1) = abs(r(1)-x0);
k = 2;
while (resarray(k-1) >= tol) && (k <= N)
r(k) = r(k-1) - (f(r(k-1))/df(r(k-1)));
resarray(k) = abs(r(k)-r(k-1));
k = k+1;
Arnab Sen on 25 Feb 2016
I do not find any flaw as such in the code you provide. But the fact is Newton method does not always gives the output for following reasons:
I. If the function does not does not intersect the x-axis (i.e. no root) at all. Few trivial example is f(x)=5 and f(x)=sin(x)+10. Another slightly non trivial example being f(x)=x/sqrt(abs(x)). Verify that if the function falls under this category.
II. If the function does have root, try to increase 'N' and the tolerance (tol) and check. And also you may try to put the initial guess 'x0' more closer to the actual root and check.
If the above does not answer your question, then provide the function and other parameters for which it's not working.
Find more on Numeric Types in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!