May-09-2020, 05:06 PM
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:
Which outputs:
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.