0

I have written a function that estimates the inverse of e and loops through values of n until the approximated value is within a given tolerance of the actual value.

Currently I use this code:

function [approx, n] = calc_e(tolerance)

for n = 1:inf
    approx = ((1-1/n)^n);
    diff = (1/exp(1)) - approx;
    if diff < tolerance, break; end
end
end

This works fine however I have been told that it could be more efficient by using a while loop but I can't work out how to do it in that way.

Can anybody shed some light on this?

3
  • I do not think that it would make any difference in matlab Commented Nov 17, 2015 at 16:05
  • furthermore, the name of the func is missleading, you are approximating 1/e, not e (which would require (1+1/n)^n Commented Nov 17, 2015 at 16:08
  • 2
    You really should avoid using built-in functions names like diff as variable names. Commented Nov 17, 2015 at 16:13

1 Answer 1

4

Simply do:

function [approx, n] = calc_e(tolerance)
n = 1;
while (1/exp(1)) - ((1-1/n)^n) >= tolerance
   n = n + 1;
end
end
Sign up to request clarification or add additional context in comments.

2 Comments

you forgot about n ... initializing, incrementing
actually you can stil have a one-liner, you can put expression for diff inside while condition and increment in the body

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.