Created
October 27, 2010 17:39
-
-
Save crankycoder/649552 to your computer and use it in GitHub Desktop.
A demonstration of the golden section search algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from math import sqrt | |
phi = (1 + sqrt(5))/2 | |
resphi = 2 - phi | |
# a and b are the current bounds; the minimum is between them. | |
# c is the center pointer pushed slightly left towards a | |
def goldenSectionSearch(f, a, c, b, absolutePrecision): | |
if abs(a - b) < absolutePrecision: | |
return (a + b)/2 | |
# Create a new possible center, in the area between c and b, pushed against c | |
d = c + resphi*(b - c) | |
if f(d) < f(c): | |
return goldenSectionSearch(f, c, d, b, absolutePrecision) | |
else: | |
return goldenSectionSearch(f, d, c, a, absolutePrecision) | |
f = lambda x: x**2 | |
def test_search(): | |
assert abs(goldenSectionSearch(f, -1, (-1 + resphi*2), 1, 1e-10)) < 1e-10 | |
print "OK!" | |
if __name__ == '__main__': | |
test_search() |
Can I please possibly get a small bit of theory on how to use this code?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cribbed from wikipedia, slightly modified so that the code actually runs if just paste it into your python shell.