필터 지우기
필터 지우기

Help with Newton's Root Method Code

조회 수: 3 (최근 30일)
Jose Trevino
Jose Trevino 2016년 2월 22일
답변: Arnab Sen 2016년 2월 25일
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!

답변 (1개)

Arnab Sen
Arnab Sen 2016년 2월 25일
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.

카테고리

Help CenterFile Exchange에서 Function Creation에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by