Python Forum
Nested Recursive Function not Returning - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Nested Recursive Function not Returning (/thread-26684.html)



Nested Recursive Function not Returning - Etotheitau - May-09-2020

I am trying to make a function that finds a local minimum of an arbitrary graph, using a recursive function. When I output the result with print(), it gives the correct value, but when I return it it returns None. Here's my code and output:
def d(x, dx, f):
    return (f(x + dx) - f(x)) / dx


def minimize(f, g, iterations, dx=0.01):

    def iterate(g, i): 
        if i == iterations:
            return (g[0]+g[1])/2 # if I 
        s = d((g[0]+g[1])/2, dx, f)

        if s > 0:
            iterate((g[0], (g[0] + g[1]) / 2), i + 1)
        elif s < 0:
            iterate(((g[0] + g[1]) / 2, g[1]), i + 1)

    return iterate(g, 0) 


def f(x):
    return (x+3)**2 # Just a random function for testing purposes.


print(minimize(f, (-23, 1), 100, 0.00001)) # This should print the x position of the minimum.

Which outputs:
Output:
"C:\Users\User\PycharmProjects\Exercises\venv\Scripts\python.exe" "C:/Users/User/PycharmProjects/Exercises/function.py" None
I am running Python 3.8 on a Windows 10 laptop with PyCharm. I don't know why it is failing to return the correct value.


RE: Nested Recursive Function not Returning - Yoriz - May-09-2020

iterate only has a return on
if i == iterations:



RE: Nested Recursive Function not Returning - Etotheitau - May-09-2020

A friend did say that I should return to iterate more instead of directly calling, my current code is:
def d(x, dx, f):
    return (f(x + dx) - f(x)) / dx


def minimize(f, g, iterations, dx=0.01):

    def iterate(g, i):

        if i == iterations:
            print((g[0]+g[1])/2)
            return (g[0]+g[1])/2
        s = d((g[0]+g[1])/2, dx, f)

        if s > 0:
            return iterate((g[0], (g[0] + g[1]) / 2), i + 1)
        elif s < 0:
            return iterate(((g[0] + g[1]) / 2, g[1]), i + 1)
        elif s == 0:
            return (g[0]+g[1])/2

    return iterate(g, 0)


def f(x):
    return x**5-4*x**4 + 2*x**2+3.27*x**2-5*x+2


print(minimize(f, (0, 3), 500, 0.0000001))
This actually returns a value, but it doesn't find the minimum correctly, which I am also kind of confused about.

Ok, never mind about what I said at the end of the last post, it does find the minimum correctly, and its all working. Putting the return statements in helped, as well as another elif for the s == 0 case. The problem is solved Smile