2012-08-09 61 views
1

編寫一個函數estimatePi()來根據印度數學家Srinivasa Ramanujan找到的公式來估計和返回Pi的值。它應該使用while循環來計算總和的項,直到最後一項小於1e-15。估計皮下面的公式給出: 按Ramanujam的估計pyschools主題5

(對不起,我無法上傳圖片)

def estimatePi(): 
import math 
def factorial(n): 
    if n == 0: 
     return 1 
    else: 
     return n * factorial(n-1) 
k=0 
final=0 
pi=0 
while pi<1e-15: 
    a=factorial(4*k) 
    b=(1103+26390*k) 
    c=factorial(k) 
    d=c**4 
    e=396**(4*k) 
    f=2*math.sqrt(2)/9801 
    final+=(a*b*f)/(d*e) 
    k+=1 
    pi=1/final 
return pi 

和,我的問題是這樣的: 預期的答案是= 3.14159265359 我的答案是= 3.14159273001

我無法找到我的錯:(。任何人都可以在這方面幫助我嗎?

+0

有一個'math.factorial()'函數可以使用。另外,我建議你使用整數進行計算,並儘可能延遲轉換爲浮點 - Python對於這些任務的大整數沒有問題。另一方面,浮點是...浮點 - 廢話精確和數學計算。 – hochl 2012-08-09 09:18:43

+0

謝謝,但我又得到了同樣的答案:( – Fasna 2012-08-09 09:33:01

回答

1

您答案是正確的。浮點數有problems with accuracy尤其適用於小數點後的大數位數;並在計算非精確值時。

您可以從您的答案中看出,它已經正確估計了小數點後5位數字的pi值。

+0

謝謝,但他們問的是相同的答案 – Fasna 2012-08-09 09:38:31

0
import math 
def factorial(n): 
if n == 0: 
    return 1 
else: 
    return n * factorial(n-1) 
def series_term(k): 
a=factorial(4*k) 
b=(1103+26390*k) 
c=factorial(k) 
d=c**4 
e=396**(4*k) 
return float(a*b)/(d*e) 
def estimatePi(): 
k=0 
final=0 
while True: 
    term = series_term(k) 
    final += term 
    if term < 1.0e-15: 
     break 
    else: 
     k += 1 
f=2*math.sqrt(2)/9801 
pi = 1.0/(final * f) 
return pi 
0

您遇到的問題不在於您的代碼,而在於您對所問問題的理解。問題狀態如下:

它應該使用while循環計算求和的項,直到最後一項小於1e-15。

讓一個變量等於1,改變while循環的條件爲:while variable>=1e-15:和while循環,設置您的變量等於總和的最後一屆。這應該會給你一個更準確的價值。對於它的價值,這會產生正確的值,但pyschools仍然沒有通過我的代碼。

3

幾件事情是你的代碼錯了我的朋友。 首先,在你的代碼中記住變量pi沒有任何形狀或形式等於final。你正在計算一個不會迭代的while循環,因爲pi明顯比1e-15更大。簡而言之,您的代碼只需在k = 0時計算公式,然後停止。 因此,這裏是一個可能的方式做到這一點:

def estimatePi(): 
     import math 
     def factorial(n): 
      if n == 0: 
       return 1 
      else: 
       return math.factorial(n) 
     k=1 # we want it at k=1 not 0 since we already have k=0 as Final 
     Final=0.31830987844 #this is the value at k=0, the first value 
     while Final>1e-15: """ Note that 1e-15 is the limiting value and we want all b values that are less than 1e-15. k=2 is the final k value where b has the last smaller number than 1e-15.""" 

      b=(2*math.sqrt(2)/9801)*(factorial(4*k)*(1103+26390*k))/((factorial(k)**4)*(396**(4*k))) 

      Final=Final+b 
      k=k+1 
      return 1/Final 
    print estimatePi() 
#This gives you the number you are looking for ---3.14159265359. 
1

這裏是我的代碼。它返回的結果與要求相同:

import math 
    def factorial(n): 
     if n == 0: 
      return 1 
     else: 
      return n * factorial(n-1) 
    def estimatePi(): 
     f=2*math.sqrt(2)/9801 
     k=0 
     RHS = 0 
     while True: 
      num = factorial(4*k)*(1103+26390*k) 
      den = (factorial(k))**4 * 396**(4*k) 
      a = f*num/den 
      RHS += a 
      if a < 1e-15: break 
      k+=1 
     return 1/RHS 
+0

也許有些解釋是爲了? – 2016-12-04 02:13:32