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.
0 件のコメント
回答 (1 件)
KALYAN ACHARJYA
2019 年 3 月 24 日
編集済み: madhan ravi
2019 年 3 月 24 日
% 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 件のコメント
Anthony Ming
2019 年 3 月 24 日
KALYAN ACHARJYA
2019 年 3 月 24 日
編集済み: KALYAN ACHARJYA
2019 年 3 月 24 日
What input you have passed to the function, please provide details?
Anthony Ming
2019 年 3 月 24 日
KALYAN ACHARJYA
2019 年 3 月 24 日
編集済み: KALYAN ACHARJYA
2019 年 3 月 24 日
@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!
この質問は閉じられています。
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!