澄清Newton-Raphson的实施

问题描述 投票:0回答:1

你能解释一下这段代码是如何工作的吗?我能理解其中的大部分内容,但cnt命令让我感到困惑。 cnt代表什么,它是如何用来解决方程式的?

t=0; %% Initial estimate of t
idx=1; %% Number of iterations
iter=zeros(1,100); %% Array to store sequence of t values
func=zeros(1,100); %% Array to store sequence of f(t) values
eps=1e-6; %% Required accuracy
n_max=100; %% Number of iterations
f=1; %% f contains f(t)
while abs(f)>eps && idx<n_max

  f=-5-exp(-t)+cos(.3*pi*t)+(.1*t*t);
  dfdt=exp(-t)-(0.3*pi*sin(0.3*pi*t))+(0.2*t);

  iter(idx)=t;
  func(idx)=f;
  idx=idx+1;

  t=t-f/dfdt;
end

cnt=idx-1;
t=linspace(0,10,100);

f=zeros(1,100);
for idx=1:100
  f(idx)=-5-exp(-t(idx))+cos(.3*pi*t(idx))+(.1*t(idx)*t(idx));
end

figure, hold on;
grid on;
plot(t,f);
scatter(iter(1:cnt),func(1:cnt),'r');
title('Newton-Raphson Example','FontSize', 12)
legend('f(t)','Iterations', 'NorthWest');
xlabel('t', 'FontSize', 12);
ylabel('f(t)','FontSize', 12);
matlab iteration mathematical-optimization numerical-methods newtons-method
1个回答
2
投票

cnt,通常代表“计数”或“计数器”,不是用来解决任何事情,而是用来绘制它。

如果我们遵循该算法,我们可以看到:

  • 最初,iterfunc被预分配为长度为100的向量 - 表明该算法预期会在这个迭代次数内收敛(或更少)。
  • 之后,当while循环结束时,cnt会跟踪实际收敛的迭代次数。
  • 最后,在创建scatter图时,cnt被用作绘图的最终索引,因此我们最终不会显示对应于iter(cnt+1:n_max)func(cnt+1:n_max)的所有零。
© www.soinside.com 2019 - 2024. All rights reserved.