0

I'm having a problem turninf1g this code into a recursive function . My main problem is trying to figure out how to check if its greater than f1 in the recursion . Th code works perfectly on its own but i wish to turn it to a recursive function if possible.

def countTerms(n):
    f1=1+1+1/math.factorial(n)
    m=1
    f2=pow((1+1/m),m)
    while f2<f1:
        m+=1
        f2=pow((1+1/m),m)
    return round(f2,2)
daveruinseverything
  • 4,775
  • 28
  • 40
DANE
  • 27
  • 4

3 Answers3

1

In general, a recursive function has an if with two cases: the base case (when the computation is done) and the recursive case (when you still need to break down the problem set a little further). In this instance, the base case is when f2 reaches or exceeds f1:

import math

def countTerms(n, m=1, f2=2):
    f1 = 2 + 1 / math.factorial(n)
    if f2 < f1:
        return countTerms(n, m=m + 1, f2=(1 + 1 / m) ** m)
    else:
        return math.round(f2, 2)

EDIT: Added explicit keyword args to the recursive call to make it more clear how m and f2 are updated for each successive iteration.

wbadart
  • 2,583
  • 1
  • 13
  • 27
  • Also, just a note, `n` stays fixed throughout the computation, and `f1` is defined purely in terms of `n`, so it stays fixed too. Therefore, you could precompute `f1` and make that the first parameter, rather than `n`, and cut down on the repeated calls to `math.factorial`. – wbadart Mar 04 '19 at 14:55
1

You can change to this:

def count_terms(n, m=1):
    f1 = 1 + 1 + 1 / math.factorial(n)
    f2 = pow((1 + 1 / m), m)
    if f2 >= f1:
        return round(f2, 2)
    else:
        m += 1
        count_terms(n, m)
Hiadore
  • 686
  • 3
  • 15
0

What you're looking for is something called tail recursion What is tail recursion?.

I assume this is a HW problem? What you want to determine are the base case, termination condition and update rule -- can you reformulate your while loop in those terms?

JoshuaF
  • 1,124
  • 2
  • 9
  • 23