Skip to content

Instantly share code, notes, and snippets.

@crankycoder
Created October 27, 2010 17:39
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save crankycoder/649552 to your computer and use it in GitHub Desktop.
Save crankycoder/649552 to your computer and use it in GitHub Desktop.
A demonstration of the golden section search algorithm
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()
@crankycoder
Copy link
Author

Cribbed from wikipedia, slightly modified so that the code actually runs if just paste it into your python shell.

@ry05
Copy link

ry05 commented May 30, 2018

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