Azzera filtri
Azzera filtri

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

2 visualizzazioni (ultimi 30 giorni)
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!

Risposta accettata

Matt Fig
Matt Fig il 16 Ott 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...

Più risposte (1)

Walter Roberson
Walter Roberson il 15 Ott 2012

Community Treasure Hunt

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

Start Hunting!

Translated by