How can I compute the sum of P (n) with a recursive function for any depth n.
Asked
Active
Viewed 75 times
-2
-
1Recursion has 2 parts: the recursive condition (or recursive call) and the base (or stopping) condition. What have you tried so far? Have you analyzed/identified those 2 conditions for your example? – Ralf Mar 25 '21 at 20:02
-
The basic recursion pattern is: create function signature, test stopping condition and return, if exit condition not met perform intermediate step and pass value to recursive function. Take a look at recursive Fibonacci as an example of a recursive Python method that computes a recurrence relationship: https://stackoverflow.com/questions/494594/how-to-write-the-fibonacci-sequence – Michael Ruth Mar 25 '21 at 20:02
-
Start off with your exit condition as `n == 1`, and `return n**-2 + n**-4 + n**-6`. Then figure out how to perform the summation for n > 1. – Michael Ruth Mar 25 '21 at 20:08
-
@MichaelRuth Yeah. I already saw that fibonacci but this one is kinda confusing to me. It might because of the way it looks. Thanks a lot tho i will check it. Pretty sure it will help me! – animoxl Mar 25 '21 at 20:11
-
@animoxl, SO expects you to at least try something and post your code. This is why I throw out a bread crumb and a link rather than posting a solution. Give it a shot, post your output vs your expected output, and the SO community will help you out. – Michael Ruth Mar 25 '21 at 20:30
3 Answers
0
Here's how you could do it:
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
lnogueir
- 1,647
- 2
- 9
- 18
0
Is something as simple as:
def P(n):
return n if n < 1 else P(n - 1) + 1/n**2 + 1/n**4 + 1/n**6
satisfactory to your needs?
cdlane
- 37,186
- 5
- 26
- 72
0
A proposal for a longer but simpler(I think) solution(with an explanation):
Because of the commutative property(a+b = b+a), you can do things backwards. This means that you can solve this equation backwards and instead of incrementing n by 1, you can start with n and decrement by 1, adding as you go. This turns out to be perfect for recursion, as all you need to do is add the terms(1/n**2 and such) with the function for a slightly smaller number, with a corner case:
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
How it works:(calculating 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
Note: Python's floats only hold so much precision.
NRO
- 78
- 7