I want to get the values from the last two iteration
1 次查看(过去 30 天)
显示 更早的评论
Hi, i am creating a program, that follows the secant method, wherein you input two guesses which are xi1, xi and a error tolerance, the problem i have here is that i do not know how to replace the newxi as xi and the last xi from the iteration as xi1. In the image we can see that as iteration 3 and beyond is has the same values all the way since i do not know how to replace xi and xi1. by the way, xi at i=0 is the first guess while xi at i=1 is the xi1 or the second guess
disp('i xi f(xi) ear') %Header
for i=0:200
if i==0
xinew=xi1; %Calculate xi
fxi=y(xinew);
elseif i==1
xinew=xi;
fxi=y(xinew);
elseif i>1
xinew=xi-((y(xi)*(xi-xi1))/(y(xi)-y(xi1))); %Calculate xi
fxi=y(xinew);
end
fprintf('%2.i %18.8f %15.8f \n',i,xinew,fxi) %Creation of rows in the iteration
0 个评论
回答(1 个)
Torsten
2022-3-24
% Tolerances, Maximum number of iterations
tolF = 1e-6;
tolX = 1e-8;
itermax = 30;
% Start values
xim2 = 6;
xim1 = 4;
fim2 = f(xim2);
fim1 = f(xim1);
% Initialization
errorF = 1.0;
errorX = 1.0;
iter = 0;
% Iteration loop
while (errorF > tolF || errorX > tolX) && iter < itermax
xi = xim1 - fim1*(xim1-xim2)/(fim1-fim2)
fi = f(xi);
errorF = abs(fi);
errorX = abs(xi-xim1)
fim2 = fim1;
fim1 = fi;
xim2 = xim1;
xim1 = xi;
iter = iter + 1;
end
% Result
xi, fi
% Function definition
function y = f(x)
y = (x-3).^2 - 4
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Financial Data 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!