My code isnt looping until answer is found

function [n] = NEWTON(x,err)
f1=@(x)(-9*x^5-8*x^3+12);
f2=@(x)(45*x^4-24*x^2);
%use equation
xnew = x - (f1(x)/f2(x));
%evaluate
if abs((xnew - x )/xnew) > err
xs = xnew;
else
x = xnew;
end
fprintf('The optimization estimate is=%f', xs);
end
I am trying to use newtons mathod to find the iptimization estimate, but it is only doing one iteration and then stopping, I am unsure how I can make it go until the answer is there within the error limit.

Answers (1)

% I am certain that you can use while loop here, Lets say new evaluated error in each iterations names as error_update
and err is err defined during pass the function input values, i.e. error limit
while err_update<err
%your code
end
Please ensure that the err_update is increasing in each iteration, so that loop does not run forever.
function [n]=NEWTON(x,err)
f1=@(x)(-9*x^5-8*x^3+12);
f2=@(x)(45*x^4-24*x^2);
err_update=0; %Initialization
while err_update<err %here err is user defined error limit
%use equation
xnew = x - (f1(x)/f2(x));
err_update=abs((xnew - x )/xnew);
x=xnew;
end
fprintf('The optimization estimate is=%f', xs);
end
Please change the required inside while loop. Hope it helps!

4 Comments

Unfortunately I am still getting the same answer as before, I noticed you said to change the required inside while loop, could you explain that?
Also thank you very much for helping me
What input you have passed to the function, please provide details?
In my book, there is an answer that I know is right so i checked it but had to change f1 and f2.
f1=@(x)2*cos(x)-(x/5);
f2=@(x)-2*sin(x)-(1/5);
and i used NEWTON(2.5,.001)
The answer should be around 1.42755
@Anthony, I dont know which book you are talking about. I have answer based on your heading question. I have trued with new f1 and f2 also its giving me different answer.
function [n]=NEWTON(x,err)
f1=@(x)(2*cos(x)-(x/5));
f2=@(x)(-2*sin(x)-(1/5));
err_update=0; %Initialization
while err_update<err %here err is user defined error limit
%use equation
xnew=x-(f1(x)/f2(x));
err_update=abs((xnew-x)/xnew)
x=xnew;
end
fprintf('The optimization estimate is=%f', xnew)
end
Here results
>> NEWTON(2.5,.001)
xnew =
0.9951
err_update =
1.5124
The optimization estimate is=0.995082>>
The issue with concept/coding (maths) logic, see the while loop failed in first iterations
err_update=0;
while loop true as 0<0.001
Next iterations
while err_update=1.5124<0.001 % Condition false
no ierations and jump to fpintf statemnet.
Hope you getting the clue!

This question is closed.

Products

Release

R2018b

Asked:

on 24 Mar 2019

Closed:

on 20 Aug 2021

Community Treasure Hunt

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

Start Hunting!