Python Forum
Nested Recursive Function not Returning
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Nested Recursive Function not Returning
#3
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
Reply


Messages In This Thread
RE: Nested Recursive Function not Returning - by Etotheitau - May-09-2020, 06:09 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  nested function return MHGhonaim 2 621 Oct-02-2023, 09:21 AM
Last Post: deanhystad
  with open context inside of a recursive function billykid999 1 588 May-23-2023, 02:37 AM
Last Post: deanhystad
  Why my function is returning None? PauloDAS 6 1,768 Jul-17-2022, 11:17 PM
Last Post: Skaperen
  return vs. print in nested function example Mark17 4 1,757 Jan-04-2022, 06:02 PM
Last Post: jefsummers
  Exit function from nested function based on user input Turtle 5 2,931 Oct-10-2021, 12:55 AM
Last Post: Turtle
  Why recursive function consumes more of processing time than loops? M83Linux 9 4,277 May-20-2021, 01:52 PM
Last Post: DeaD_EyE
Question Stopping a parent function from a nested function? wallgraffiti 1 3,690 May-02-2021, 12:21 PM
Last Post: Gribouillis
  Pausing and returning to function? wallgraffiti 1 2,171 Apr-29-2021, 05:30 PM
Last Post: bowlofred
  Combine Two Recursive Functions To Create One Recursive Selection Sort Function Jeremy7 12 7,398 Jan-17-2021, 03:02 AM
Last Post: Jeremy7
  Execution of Another Recursive Function muzikman 5 3,033 Dec-04-2020, 08:13 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020