2017-03-16 43 views
0

近似公式(1-1/n)**n的n的值,其公式中的值n1/e之間的差值小於0.0001。如何使用python編寫給定條件的算法

我們該如何在python中使用while和for循環。

我嘗試使用while用下面的代碼

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) 

但由於檢查不while之前定義的程序不能運行。

有沒有更好的解決方案?

+1

'(1-1/n)^ n'不會做你認爲它做的事。 –

+0

如果符合檢查條件,則使用'while True'並中斷; –

+0

你的意思是:'(1-1/n)** n'? – linusg

回答

1

之初定義檢查,並與**取代^,因爲後者是寫功率蟒蛇

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) 

順便說一句正確的方法,^是蟒蛇按位異或運算符。你可以在這裏找到更多的描述: http://python-reference.readthedocs.io/en/latest/docs/operators/bitwise_XOR.html