Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@officialcjunior
Created January 1, 2021 12:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save officialcjunior/76cbadb1d516e71003f100e6f5027199 to your computer and use it in GitHub Desktop.
Save officialcjunior/76cbadb1d516e71003f100e6f5027199 to your computer and use it in GitHub Desktop.
Python script to find the minimize unimodal expressions using the golden section method | optimization technique
import math
invphi = (math.sqrt(5) - 1) / 2 # 1 / phi
invphi2 = (3 - math.sqrt(5)) / 2 # 1 / phi^2 ig
def gssrec(f, a, b, tol=1e-5, h=None, c=None, d=None, fc=None, fd=None):
(a, b) = (min(a, b), max(a, b))
if h is None: h = b - a
if h <= tol: return (a, b)
if c is None: c = a + invphi2 * h
if d is None: d = a + invphi * h
if fc is None: fc = f(c)
if fd is None: fd = f(d)
if fc < fd:
print ("a =", a , "b =", b)
print ("f(", c, ") = ", f(c), "\nf(", d, ") = ", (f(d)), "\n")
return gssrec(f, a, d, tol, h * invphi, c=None, fc=None, d=c, fd=fc)
else:
return gssrec(f, c, b, tol, h * invphi, c=d, fc=fd, d=None, fd=None)
## change f(n) here ->
f = lambda x: math.sin(x) * math.exp(x)
## interval ->
a0 = -2
b0 = 1
count = 0
print (gssrec(f, a0, b0))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment