Newton Raphson Method Errors

조회 수: 20 (최근 30일)
Shakil Rahman
Shakil Rahman 2016년 10월 21일
답변: Meysam Mahooti 2019년 12월 5일
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

답변 (2개)

Mischa Kim
Mischa Kim 2016년 10월 21일
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
Shakil Rahman
Shakil Rahman 2016년 10월 21일
편집: Shakil Rahman 2016년 10월 21일
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 2016년 10월 21일
  • 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)

댓글을 달려면 로그인하십시오.


Meysam Mahooti
Meysam Mahooti 2019년 12월 5일

카테고리

Help CenterFile Exchange에서 Newton-Raphson Method에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by