While 循环和收敛测试
While Loops and Testing for Convergence
我一直在尝试使用 while 循环来测试 X(n) = X(n-1)+((-1)^n)/n) 的收敛性,因为 n 趋于无穷大。我似乎无法让我的代码工作。我知道根据定义 Xn 是一个序列并且 Xn 有一个限制如果对于所有 E>0 存在 K E N 使得 |Xn - L| < E.(很抱歉,我不确定如何在此处插入希腊字母)。最初我尝试了这个但它没有用,然后考虑而不是找到与 L 的收敛,而是使用两个后续元素之间的差异:|X(n) - X(n-1) | < E for n -> 无穷大。
我不确定哪里出错了。
K=1;
x(K)=x(K-1)+((-1)^K)/K;
eps=0.0001;
L=0;
while abs(x(K)-x(K-1))>eps && K<10^5
K=K+1;
x(K+1)=x(K-1)+((-1)^K)/K;
end
sprintf('K is %d, x(K)=%f', [K, x(K)])
if abs(x(K)-x(K-1))< eps && K<10^5
% test that condition hold for any n>K
n=fix(rand()*100)+K;
x_n=x(n-1)+((-1)^n)/n; %corresponds to x(n)
if abs(x_n-(x(n-1)+((-1)^n)/n))<eps
sprintf(['the test did not fail\n',...
' The sequence satisfies the definition'])
else
sprintf('the test for convergence failed')
end
else
sprintf('The sequence did not converge over %d iterations', [K])
end
在开头添加以下两行,使您的代码成为运行、
x(1)=1;
K=2;
然后绘制
plot(abs(x))
你可以看到这是一个振荡函数,它不会收敛。
我一直在尝试使用 while 循环来测试 X(n) = X(n-1)+((-1)^n)/n) 的收敛性,因为 n 趋于无穷大。我似乎无法让我的代码工作。我知道根据定义 Xn 是一个序列并且 Xn 有一个限制如果对于所有 E>0 存在 K E N 使得 |Xn - L| < E.(很抱歉,我不确定如何在此处插入希腊字母)。最初我尝试了这个但它没有用,然后考虑而不是找到与 L 的收敛,而是使用两个后续元素之间的差异:|X(n) - X(n-1) | < E for n -> 无穷大。
我不确定哪里出错了。
K=1;
x(K)=x(K-1)+((-1)^K)/K;
eps=0.0001;
L=0;
while abs(x(K)-x(K-1))>eps && K<10^5
K=K+1;
x(K+1)=x(K-1)+((-1)^K)/K;
end
sprintf('K is %d, x(K)=%f', [K, x(K)])
if abs(x(K)-x(K-1))< eps && K<10^5
% test that condition hold for any n>K
n=fix(rand()*100)+K;
x_n=x(n-1)+((-1)^n)/n; %corresponds to x(n)
if abs(x_n-(x(n-1)+((-1)^n)/n))<eps
sprintf(['the test did not fail\n',...
' The sequence satisfies the definition'])
else
sprintf('the test for convergence failed')
end
else
sprintf('The sequence did not converge over %d iterations', [K])
end
在开头添加以下两行,使您的代码成为运行、
x(1)=1;
K=2;
然后绘制
plot(abs(x))
你可以看到这是一个振荡函数,它不会收敛。