필터 지우기
필터 지우기

Having a slight problem with Newton-Raphson loop. No errors in command window..

조회 수: 2 (최근 30일)
Hi everybody!
First, thank you very much for answering my previous question about the anonymous functions.
The new issue is:
I'm trying to make Matlab solve equations using Newton - Raphson method. So far I've written my code trying to follow the guide on youtube. The only problem is that the user there is using symbolic math toolbox, which I don't have. So I am trying to use the " Numerical differentiation " method and use anonymous function as an input.
Here is my code:
function [root, iterations] = newtonRaphson(funIn, guessValue)
x = guessValue;
for u=0:2814 % max number of iterations
y=x;
derivative = @(x) (funIn(x+0.001)-funIn(x))/0.001; % Numerical diff.
x=y-funIn(x)/derivative(x); % Newton-Raphson formula.
if x==y
root = x
iterations = u
break
end
end
I then use " newtonRaphson(@(x) sin(x) - x, 10) " as an input. The function, unfortunately does nothing, the command window is absolutely empty and I don't even know what the error is. Any ideas guys?
Thank you very much for your help guys!

채택된 답변

Matt Fig
Matt Fig 2012년 10월 16일
To elaborate on Walter's answer. You are comparing floating point numbers for absolute equality - a mistake in general.
Instead, set a tolerance in the code:
tol = 1e-10;
Then your conditional should read:
abs(x-y)<tol
Also, it is a good idea to define your outputs for a default case, for when the conditional is not met but the user wants two return arguments...

추가 답변 (1개)

Walter Roberson
Walter Roberson 2012년 10월 15일

카테고리

Help CenterFile Exchange에서 Newton-Raphson Method에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by