-2

I am getting a recursion error from the code below. Could anyone please explain why this is occurring and what a potential fix for the code could be? In this code I am trying to use the original function n1 and use this to find n2 and n3 by using the previous function calculated and storing them in the functions list I created. In other words,i am attempting to do a recursive function inside the for loop. Then I want to evaluate a particular function stored from the list at (h) on the last line.

import numpy as np 
f = lambda x: np.sin(10*x)
x0 = 0.5
h  = 0.1 
n1 = lambda h: (f(x0+h)-f(x0-h))/(2*h)
functions = []
functions.append(n1)

for i in range(0,2):
    a = 1/(1-4**(i+2-1))
    b = -4**(i+2-1)/(1-4**(i+2-1))  
    nh = lambda h: a*functions[i](h) + b*functions[i](h/2)
    functions.append(nh)
print(functions[1](h))
    

RecursionError: maximum recursion depth exceeded

JCX1010
  • 1
  • 3
  • 1
    Perhaps you would like to [edit] your question and explain what your code is supposed to do. – khelwood Mar 17 '22 at 14:41
  • This happens because the nh function you insert in the functions list contains a reference to `functions[i]` which is the function inserted itself. – Peterrabbit Mar 17 '22 at 14:45
  • 1
    You probably want `functions[i-1]` instead, but you also need to ensure the *value* of `a`, `b`, and `i` are used in the definition of `nh`, not just the *names*. – chepner Mar 17 '22 at 14:56

1 Answers1

0

The problem is that functions[i] is evaluated at the time each function is called, when the loop has finished iterating, and i is 2. This creates an infinite recursive reference to functions[2].

A way around this is to put your function creation code into a separate function, which creates an enclosed scope for a, b and i.

def make_function(n, previous_function):
    a = 1/(1-4**(n+2-1))
    b = -4**(n+2-1)/(1-4**(n+2-1))  
    return lambda h: a * previous_function(h) + b * previous_function(h / 2)

for i in range(2):
    functions.append(make_function(i, functions[-1]))
print(functions[1](h))
Stuart
  • 9,597
  • 1
  • 21
  • 30