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?
1 Answer 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
(1-1/n)^ndoesn't do what you think it does.while Trueand break if condition on check is met;(1-1/n)**n?