# Help with Newton's Root Method Code

62 views (last 30 days)
Jose Trevino on 22 Feb 2016
Answered: Arnab Sen on 25 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;
end
end
Thank you!

Arnab Sen on 25 Feb 2016
Hi Jose,
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.
{"ft_lang_label":"__label__en","ft_lang_prob":0.8841488,"math_prob":0.97691035,"size":703,"snap":"2021-21-2021-25","text_gpt3_token_len":168,"char_repetition_ratio":0.14878398,"word_repetition_ratio":0.0,"special_character_ratio":0.24324325,"punctuation_ratio":0.103896104,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.99943316,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-05-14T23:12:30Z\",\"WARC-Record-ID\":\"<urn:uuid:70ab96b8-d42c-4c68-b9a3-d4527ceb8888>\",\"Content-Length\":\"110608\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:5f8feeba-34bd-4d1d-893d-0500bf680bec>\",\"WARC-Concurrent-To\":\"<urn:uuid:6df7378a-4408-4749-bb32-5d52718f7d74>\",\"WARC-IP-Address\":\"23.197.108.134\",\"WARC-Target-URI\":\"https://www.mathworks.com/matlabcentral/answers/269314-help-with-newton-s-root-method-code\",\"WARC-Payload-Digest\":\"sha1:KPPR3NO6LVKZEBJDNLT64A4RWE7ATNA6\",\"WARC-Block-Digest\":\"sha1:OYFAN6EAVYABPT3MVTGHL7VWXXDUVJ3Q\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-21/CC-MAIN-2021-21_segments_1620243991829.45_warc_CC-MAIN-20210514214157-20210515004157-00581.warc.gz\"}"}