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

2 vues (au cours des 30 derniers jours)
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!

Réponse acceptée

Matt Fig
Matt Fig le 16 Oct 2012
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...

Plus de réponses (1)

Walter Roberson
Walter Roberson le 15 Oct 2012

Community Treasure Hunt

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

Start Hunting!

Translated by