编辑
这个答案并不能真正解决用户的问题。但是由于用户想要的是一个近似于 1/e 的循环,所以这里有一些可能性:
一种快速方法:
tic
N = 1e6;
N1 = 1;
N2 = N1 + N - 1;
err_exp = 1e-7;
ctrl = 1;
while ctrl
n = N1:N2; eqn = (1 - (1 ./ n)) .^ n;
inds = find(abs(eqn - 1/exp(1)) < err_exp, 1, 'first');
if ~isempty(inds)
ctrl = 0;
else
N1 = N1 + N;
N2 = N1 + N - 1;
end
end
fprintf('n must be at least %d\n', N1 + inds - 1)
toc
% Elapsed time is 0.609669 seconds.
更好的方法是二分搜索:
tic
N = 1e6;
a = 1 / exp(1);
err_exp = 1e-15;
ctrl = 1;
n = 1;
% 1º Step: find starting values for n1 and n2
while ctrl
eqn = (1 - (1 / n)) ^ n;
ctrl = abs(eqn - a) > err_exp;
if ctrl
n1 = n;
n = 2 * n;
end
end
n2 = n;
% 2º step: search dichotomically between the extremes
ctrl = 1;
while ctrl
if n2 - n1 < N
n = n1:n2; eqn = (1 - (1 ./ n)) .^ n;
n = find(abs(eqn - a) < err_exp, 1, 'first');
eqn = eqn(n);
n = n1 + n - 1;
ctrl = 0;
else
n = floor((n1 + n2 + 1) / 2);
eqn = (1 - (1 / n)) ^ n;
chck = abs(eqn - a) > err_exp;
if chck
n1 = n;
else
n2 = n;
end
end
end
toc
% Elapsed time is 0.231897 seconds.
[abs(eqn - a), err_exp]
[n1 n n2]
就是图个好玩儿。