Newton Raphson Method Errors

17 views (last 30 days)
Shakil Rahman
Shakil Rahman on 21 Oct 2016
Answered: Meysam Mahooti on 5 Dec 2019
Having errors with my code and not quite sure how to fix it. As you can probably see from the code below, I am calling the values f and df from two other files. The code directly below this is stored in a file called NRM2016.m whereas the f variable and df variable are stored in funct.m and dfunct.m respectively.
What I am trying to do is allow the users to input an initial guess and an initial accuracy. The code then stores this and applies it to the function and its differential and then store it to a text file. (the writing to text file isn't an issue so I have omitted the code: as ignore the 'if true' part that starts the code below that isn't there in the original)
1: Main Script
if true
%Initial conditions for NRM
xinit = input('Enter a value for initial guess (Xo):');
epsilon = input('Enter a value for the required accuracy (Eps):');
x = xinit;
xold = xinit;
for i = 0:inf
x = x-f/df;
error = abs(x-xold);
xold = x;
if(error<epsilon)
break;
end
end
2: Funct.m & dfunct.m's contents
%creates symbolic variables/functions
syms x
%Below is the cubic equation we wish to differentiate
f = x^3 + 11*x^2 + 4*x - 60;
%Differentiate funct(x) with respect to x
df = diff(y,x);
I am taking the initial value as 1.8 to begin with and the required accuracy as 1e-13 however it just isn't working. The differential is working fine as well as the input variables. I just don't know why it isn't doing Newton Raphson Method correctly. Can anyone help? thanks

Answers (2)

Mischa Kim
Mischa Kim on 21 Oct 2016
Shakil, convert the symbolic equations to numeric and you are good to go:
function NR(xinit, epsilon)
x = xinit;
xold = xinit;
syms y
sf = y^3 + 11*y^2 + 4*y - 60;
sdf = diff(sf,y);
f = matlabFunction(sf);
df = matlabFunction(sdf);
while true
x = x - f(x)/df(x);
error = abs(x-xold);
xold = x;
fprintf('%10.4f %10.4f\n', x, error);
if(error<epsilon)
break;
end
end
end
and use, e.g.
NR(1, 1e-3)
  3 Comments
Shakil Rahman
Shakil Rahman on 21 Oct 2016
Edited: Shakil Rahman on 21 Oct 2016
Still getting an error. The function and its differential are working perfectly but I'm getting the same error as I was getting before. Thanks for the help by the way.
Mischa Kim
Mischa Kim on 21 Oct 2016
  • I recommend using functions over scripts. But, yes, in general your code should work.
  • You are using x as a symbolic and as a numeric variable. Keep them separate. I used y for the symbolic expressions.
  • Make sure your code matches mine, e.g. x = x - f(x)/df(x)

Sign in to comment.


Meysam Mahooti
Meysam Mahooti on 5 Dec 2019

Community Treasure Hunt

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

Start Hunting!