pythonexcelcalculus

Converting a python recursive function into excel


So, I have to run a recursive function times but it's going to take too long to actually print out all the values. Thus, my professor recommended using Excel but I don't know Excel at all. I need help converting the code into Excel.

It's probably easy for someone who knows Excel.

def a(n):
    k=3.8
    if n==0:
        return .5
    else:
        return k*a(n-1)*(1-a(n-1))

for i in range(100):
    print(a(i))

All i know is that you use the lambda() function in excel


Solution

  • You don't need to use excel. You just need to use a better algorithm. The easiest way to prevent the exponential time complexity is don't re-calculate the same value twice:

    def a(n):
        k = 3.8
        if n==0:
            return .5
        else:
            x = a(n - 1)
            return k*x*(1-x)
    
    for i in range(100):
        print(a(i))
    

    In Python, you should avoid recursion, though, since Python doesn't optimize recursion and you will run out of stack space. This is easy to convert to an iterative algorithm, though:

    def b(n):
        k = 3.8
        prev = curr  = 0.5
        for i in range(1, n + 1):
            curr = k * prev * (1 - prev)
            prev = curr
        return curr