May-09-2020, 06:09 PM
(This post was last modified: May-09-2020, 06:27 PM by Etotheitau.)
A friend did say that I should return to iterate more instead of directly calling, my current code is:
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
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