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

Community Treasure Hunt

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

Start Hunting!

Translated by