Reputation: 31
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)
Upvotes: 2
Views: 481
Reputation:
EDIT
This answer doesn't really solve the user's problem. But since what the user wanted was a loop to approximate 1/e, here are some possibilities:
One quick approach:
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.
A better approach is the dichotomic search:
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]
Just for the fun of it.
Upvotes: 1
Reputation: 8459
OK so if I run this code
a=exp(1)
clear
builtin=exp(1)
I get
a =
2.7183
builtin =
2.7183
and this error
However if I run this code
a=exp(1)
clear
builtin=exp(1)
clear
a=exp(1)
I get no error!
This is R2012b on Mac OSX.
Upvotes: 1
Reputation: 30589
Type whos
and make sure abs
and exp
aren't listed. If they are listed as variables, clear them with:
clear abs whos
Then make sure there is no where else above this code that sets abs
and whos
as variables.
For the record, it seems there is some strange version-specific popup error that happens when you do builtin=exp(1)
. David pointed this out. Unfortunately, I can't reproduce it with R2013b 64-bit.
Upvotes: 1