Golden Section Search

Max or Min of Equation - Python


Using Golden Section Search to Find Max or Min of Equation

The Golden Section Search can be used to find the maximum or minimum of a single equation. The method starts with two initial guesses, xlow and xhigh, that bracket the minimum or maximum we are interested in. We include the maximum number of iterations, and the acceptable error. The objective equation is placed in the second nested function. At three locations in the maximization program we use f1 > f2. We can turn the greater that sign around at the three locations, f1 < f2, and create a minimization program. Suggested reading is Numerical Methods for Engineers, Fifth Edition by Chapra and Canale.



#Golden Section Search for Maximum or Substitution for Min
def Gold(xlow, xhigh, maxit, es):
#Nested function contains objective function
 def f(x):
  f = (450 * x / (8 * (x + 22) + 10 * x + 120)) ** 2 / x
  return f
 R = (5**.5 - 1) / 2
 xL = xlow
 xu = xhigh
 iter = 1
 d = R * (xu - xL)
 x1 = xL + d
 x2 = xu - d
 f1 = f(x1)
 f2 = f(x2)
 if f1 > f2: #if f1 < f2: Substitution for Min
  xopt = x1
  fx = f1
 else:
  xopt = x2
  fx = f2

 while True:
  d = R * d
  if f1 > f2: #if f1 < f2: Substitution for Min
   xL = x2
   x2 = x1
   x1 = xL + d
   f2 = f1
   f1 = f(x1)
  else:
   xu = x1
   x1 = x2
   x2 = xu - d
   f1 = f2
   f2 = f(x2)
  iter = iter + 1
  if f1 > f2: #if f1 < f2: Substitution for Min
   xopt = x1
   fx = f1
  else:
   xopt = x2
   fx = f2
  if xopt != 0:
   ea = (1 - R) * abs((xu - xL) / xopt) * 100
  if ea <= es or iter >= maxit:
   break
 print('iter=',iter)
 print('xopt=',xopt)
 print('f=',fx)
 return xopt
#Main program calling function Gold
Gold(.1,100,100,.001)

#Output
# xopt= 16.444405588708648
# f= 9.501689189175927

# The maximum is (x,y) or (16.444,9.501)






This website consists of example problems from numerical methods for engineers. The first examples apply to roots, plotting roots, maximums, mininums, and optimization problems. You have enough examples so that you become familiar with the syntax used in Python. The examples have been tested and the output of the programs are listed in the comments for each. All programs were run on Python using the PyCharm Community interface. They were run on an older laptop with 8GB of RAM. If you have never used Python, I recommend the manual Introduction to Engineering Python by Steve Larsen. It is availble on Amazon.











Introduction to Engineering Python: For First Year Engineering Students