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

1 回表示 (過去 30 日間)
Kokalz
Kokalz 2012 年 10 月 15 日
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 Center および File ExchangeNewton-Raphson Method についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by