Skip to content

Instantly share code, notes, and snippets.

@iamFIREcracker
Created August 3, 2012 07:04
Show Gist options
  • Save iamFIREcracker/3245266 to your computer and use it in GitHub Desktop.
Save iamFIREcracker/3245266 to your computer and use it in GitHub Desktop.
Python implementation of the ternary search algorithm
#!/usr/bin/env python
from __future__ import print_function
from __future__ import division
def maximize(func, a, b, precision):
(left, right) = (a, b)
while True:
if right - left <= precision:
return (left + right) / 2
left_third = ((2 * left) + right) / 3
right_third = (left + (2 * right)) / 3
if func(left_third) < func(right_third):
(left, right) = (left_third, right)
else:
(left, right) = (left, right_third)
def minimize(func, a, b, precision):
def neg(func):
def wrapper(*args, **kwargs):
return -1 * func(*args, **kwargs)
return wrapper
return maximize(neg(func), a, b, precision)
def f(x):
return - x**2 + 3 * x
def f1(x):
return abs(x + 1)
def _main():
print("Max: {:6f}".format(maximize(f, -2, 5, 1e-6)))
print("Min: {:6f}".format(minimize(f1, -2, 5, 1e-6)))
if __name__ == '__main__':
_main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment