簡體   English   中英

P(n) 和遞歸 function

[英]Sum of P(n) with a recursive function

對於任何深度 n,如何使用遞歸 function 計算 P (n) 的總和。

問題

你可以這樣做:

def P(n, k = 1, currentSum = 0):
    if k > n:
        return currentSum
    currentSum += 1/k**2 + 1/k**4 + 1/k**6
    return P(n, k+1, currentSum)
    
print(P(3)) # 3.4529535322359397                                                                                                                               

是不是很簡單:

def P(n):
    return n if n < 1 else P(n - 1) + 1/n**2 + 1/n**4 + 1/n**6

滿足您的需求?

一個更長但更簡單(我認為)解決方案的提案(附有解釋):
由於交換性質(a+b = b+a),你可以倒着做事。 這意味着您可以反向求解此方程,而不是將 n 遞增 1,您可以從 n 開始並遞減 1,然后添加 go。 事實證明,這非常適合遞歸,因為您需要做的就是在 function 中添加術語(1/n**2 等)以獲得稍小的數字,並帶有一個角盒:

def P(n):
  if n == 0:
    return 0
  t1 = n**-2#** is the python syntax for raising powers
  t2 = n**-4
  t3 = n**-6
  sum_of_terms = t1+t2+t3
  return sum_of_terms + P(n-1)
print(P(100))
#3.7346498674943076

它是如何工作的:(計算 P(3))

 1. Start with 1/9 + 1/81 + 1/729 
 2. Add that to P(2): 
    a. Start with 1/4 + 1/16 + 1/64
    b. Add that to P(1)
        i. Start with 1/1 + 1/1 + 1/1
        ii. Add that to P(0)
        iii. To prevent division by zero, return 0
    c. So the sum of that is 3
 3. So the sum  of that is 3.328125
So the total is 3.4529535322359397

注意:Python 的浮點數只能保持這么高的精度。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM