-
-
Save stevenyepes/9df56addd35ad07af928c0fa51008e15 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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment