2

I am trying to do an approximation of 1/e

I keep getting an error saying index exceeds matrix dimensions. Why?

n = 0;
eqn = 0;

while abs(eqn - (1/exp(1))) > .0001
n = n+1;
eqn = (1 - (1/n))^n;

end

nsav = n;
appr = eqn;
builtin = 1/exp(1);
fprintf ('The built in value is %.4f\n' , builtin)
fprintf ('The approximation is %.4f\n', appr)
fprintf ('The value of n required for such accuracy is %d\n', nsav)
4

3 回答 3

1

编辑

这个答案并不能真正解决用户的问题。但是由于用户想要的是一个近似于 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]

就是图个好玩儿。

于 2013-11-05T23:26:37.660 回答
1

键入并whos确保未列出。如果它们被列为变量,请使用以下命令清除它们:absexp

clear abs whos

然后确保在此代码之上没有其他地方设置abswhos作为变量。

作为记录,当您这样做时,似乎会发生一些奇怪的特定于版本的弹出错误builtin=exp(1)。大卫指出了这一点。不幸的是,我无法用 R2013b 64 位重现它。

于 2013-11-05T23:28:45.107 回答
1

好的,如果我运行这段代码

a=exp(1)

clear

builtin=exp(1)

我明白了

a =
    2.7183
builtin =
    2.7183

这个错误

在此处输入图像描述

但是,如果我运行此代码

a=exp(1)

clear

builtin=exp(1)

clear

a=exp(1)

我没有错误!

这是 Mac OSX 上的 R2012b。

于 2013-11-05T23:53:01.250 回答