0

Approximate the value of n for the formula (1-1/n)**n for which the difference between the value of n in the formula and 1/e is less than 0.0001.

How can we do using while and for loop in python .

I tried using while with the following code

from math import exp
value = 1/exp(1) # e being the exponential
n = 1;
while check < 0.0001:
 n=n+1
 formula = (1-1/n)^n
 check = value - formula
 if check <0.0001:
 print(n) 

but since check is not defined before while the program doesn't run.

Is there any better solution?

asked Mar 16, 2017 at 20:04
4
  • 1
    (1-1/n)^n doesn't do what you think it does. Commented Mar 16, 2017 at 20:05
  • use while True and break if condition on check is met; Commented Mar 16, 2017 at 20:06
  • Do you mean: (1-1/n)**n? Commented Mar 16, 2017 at 20:06
  • Yes ** is the correct one thanks Commented Mar 16, 2017 at 20:29

1 Answer 1

1

Define check at the beginning, and replace ^ with **, as the latter one is the correct way to write power in python

import math
value = 1/math.exp(1) # e being the exponential
n = 1
check=1
while check > 0.0001:
 n=n+1
 formula = (1-1/n)**n
 check = value - formula
print(n) 

By the way, ^ is the bitwise xor operator in python. You can look here for further description: http://python-reference.readthedocs.io/en/latest/docs/operators/bitwise_XOR.html

answered Mar 16, 2017 at 20:07
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.