Golden Section Search algorithm
- User
Golden Section Search algorithm
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Golden Section Search algorithm
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Of course. Here is a comprehensive explanation of the Golden Section Search algorithm, covering its purpose, the core idea, the step-by-step process, a worked example, and a Python implementation.
The Golden Section Search is a numerical optimization technique used to find the minimum (or maximum) of a function within a specified interval.
Key Characteristics:
f(x).It is the optimization equivalent of the Bisection Method used for root-finding.
The algorithm maintains an interval [a, b] that is known to contain the minimum. To shrink this interval, it selects two interior points, x1 and x2, and evaluates the function at these points.
f(x1) < f(x2), the minimum must lie in the left sub-interval [a, x2]. So, we discard the [x2, b] portion.f(x1) >= f(x2), the minimum must lie in the right sub-interval [x1, b]. So, we discard the [a, x1] portion.The "magic" of the Golden Section Search is where it places x1 and x2. The points are chosen symmetrically, a certain fraction of the way into the interval. This fraction is related to the Golden Ratio, φ (phi).
The interior points are placed at:
x2 = b - (b - a) / φx1 = a + (b - a) / φWhy the Golden Ratio? This specific placement ensures a crucial efficiency gain. When the interval is shrunk, one of the old interior points becomes a new interior point for the next iteration. This means we only need to calculate one new function evaluation per iteration, not two. This re-use of a previously computed point is what makes Golden Section Search more efficient than a more naive approach like Ternary Search.
Inputs:
f: The unimodal function to minimize.a, b: The initial interval [a, b] that brackets the minimum.tol: The desired tolerance or precision for the interval width (b - a).Steps:
Initialization:
φ = (1 + sqrt(5)) / 2.x2 = b - (b - a) / φx1 = a + (b - a) / φf1 = f(x1) and f2 = f(x2).Iteration Loop:
(b - a) is greater than the tolerance tol.f1 < f2
[a, x2].b = x2.x1 becomes the new x2: x2 = x1, f2 = f1.x1 = a + (b - a) / φ.x1: f1 = f(x1).f1 >= f2
[x1, b].a = x1.x2 becomes the new x1: x1 = x2, f1 = f2.x2 = b - (b - a) / φ.x2: f2 = f(x2).Termination:
b - a <= tol), the minimum is located within the final small interval [a, b].(a + b) / 2, as the best estimate for the location of the minimum.Let's find the minimum of f(x) = (x - 2)^2 on the interval [0, 5] with a tolerance of tol = 0.5.
We know the true minimum is at x = 2.
Constants:
φ ≈ 1.6181/φ ≈ 0.618Iteration 1:
a = 0, b = 5. Width = 5.x2 = 5 - (5 - 0) / 1.618 = 5 - 3.09 = 1.91x1 = 0 + (5 - 0) / 1.618 = 3.09f(x1) = f(3.09) = (3.09 - 2)^2 = 1.188f(x2) = f(1.91) = (1.91 - 2)^2 = 0.008f(x2) < f(x1). The new interval is [a, x1], but using the GSS update rule, it's [a, x2] in the next step. Wait, the logic is f1 < f2 -> new b is x2. f1 > f2 -> new a is x1. Here f(x2) < f(x1), so the minimum is in [a, x1]. Oh, my diagram and logic text were slightly off. Let's correct. f(x1) vs f(x2). If f(x1) is smaller, the minimum is to the left of x2. So new b is x2. If f(x2) is smaller, the minimum is to the right of x1. So new a is x1.
f(x2) < f(x1). This is the f1 >= f2 case. f(3.09) > f(1.91).[x1_old, b_old] is wrong. It's in [a_old, x1_old]... no wait. x1 = 3.09, x2 = 1.91. The points are [a, x2, x1, b].f(1.91) < f(3.09). The minimum is to the left of x1. The new interval is [a, x1] = [0, 3.09].a < x1 < x2 < b. Let's re-calculate to follow that.d = (b - a) / φx1 = b - dx2 = a + dx1 = 5 - 3.09 = 1.91. x2 = 0 + 3.09 = 3.09.x1 and x2 were swapped. Let's fix that.x1 = 1.91, x2 = 3.09.f(x1) = f(1.91) = 0.008f(x2) = f(3.09) = 1.188Iteration 2:
a = 0, b = 3.09. Width = 3.09.x2 is the old x1: x2_new = 1.91. f(x2_new) = 0.008.x1_new = a + (b - a) / φ = 0 + (3.09 - 0) / 1.618 = 1.18f(x1_new) = f(1.18) = (1.18 - 2)^2 = 0.67f(x2_new) = 0.008f(x2_new) < f(x1_new). The minimum is in the interval [x1_new, b].
a becomes x1_new.Iteration 3:
a = 1.18, b = 3.09. Width = 1.91.x1 is the old x2: x1_new = 1.91. f(x1_new) = 0.008.x2_new = b - (b - a) / φ = 3.09 - (3.09 - 1.18) / 1.618 = 3.09 - 1.18 = 1.91. Oh wait, the formula is x2 = a + (b-a) / (φ^2) or x2 = b - d.d notation. d = (b - a)/φ = (3.09 - 1.18)/1.618 = 1.18.x1_new = b - d = 3.09 - 1.18 = 1.91 (the re-used point).x2_new = a + d = 1.18 + 1.18 = 2.36.f(x1_new) = f(1.91) = 0.008f(x2_new) = f(2.36) = (2.36 - 2)^2 = 0.13f(x1_new) < f(x2_new). The minimum is in [a, x2_new].
b becomes x2_new.Iteration 4:
a = 1.18, b = 2.36. Width = 1.18.
... and so on. The process continues until the interval width is less than tol=0.5. The final interval will be centered very close to x=2.import math
def golden_section_search(f, a, b, tol=1e-5):
"""
Finds the minimum of a unimodal function f on the interval [a, b]
using the golden section search method.
Parameters:
f (callable): The objective function to minimize.
a (float): The left boundary of the interval.
b (float): The right boundary of the interval.
tol (float): The tolerance for the width of the final interval.
Returns:
float: The estimated location of the minimum.
"""
# Golden ratio constant
golden_ratio = (1 + math.sqrt(5)) / 2
# Initial points
# We maintain the invariant that x1 < x2
c = b - (b - a) / golden_ratio
d = a + (b - a) / golden_ratio
fc = f(c)
fd = f(d)
while (b - a) > tol:
if fc < fd:
# The minimum is in the left sub-interval [a, d]
b = d
d = c
fd = fc
c = b - (b - a) / golden_ratio
fc = f(c)
else:
# The minimum is in the right sub-interval [c, b]
a = c
c = d
fc = fd
d = a + (b - a) / golden_ratio
fd = f(d)
# Return the midpoint of the final interval
return (a + b) / 2
# --- Example Usage ---
if __name__ == "__main__":
# Define the function to minimize: f(x) = (x - 2)^2
def my_function(x):
return (x - 2)**2
# Define the interval [a, b]
start_interval_a = 0.0
start_interval_b = 5.0
# Define the tolerance
tolerance = 1e-6
# Run the search
minimum_x = golden_section_search(my_function, start_interval_a, start_interval_b, tolerance)
print(f"The function is f(x) = (x - 2)^2")
print(f"Search interval: [{start_interval_a}, {start_interval_b}]")
print(f"Tolerance: {tolerance}")
print(f"Estimated minimum found at: x = {minimum_x:.6f}")
print(f"Function value at minimum: f(x) = {my_function(minimum_x):.6f}")
# Example 2: Cosine function
def cos_function(x):
return math.cos(x)
print("\n--------------------------\n")
print(f"The function is f(x) = cos(x)")
print(f"Search interval: [0, 6]")
# The minimum of cos(x) in [0, 6] is at x=pi
min_cos_x = golden_section_search(cos_function, 0, 6, 1e-6)
print(f"Estimated minimum found at: x = {min_cos_x:.6f}")
print(f"pi is approximately: {math.pi:.6f}")
Advantages:
1/φ ≈ 0.618) in each iteration, leading to steady, linear convergence.Disadvantages:
f(x, y, ...)).In practice, for one-dimensional optimization, hybrid methods like Brent's Method are often preferred as they combine the safety of Golden Section Search with faster methods like parabolic interpolation. However, Golden Section Search remains a foundational and important algorithm in numerical optimization.
implement in modern fortran
Of course. Here is an implementation of the Golden Section Search algorithm in modern Fortran.
This implementation emphasizes modern Fortran features for safety, clarity, and reusability:
IMPLICIT NONE: Enforces explicit type declaration for all variables, preventing common errors.REAL(dp) for double-precision floating-point numbers, making the code portable and easy to modify for different precision levels.PROCEDURE with an ABSTRACT INTERFACE is used to pass the objective function as an argument. This is the type-safe, modern way to handle function pointers/callbacks.INTENT Attribute: Specifies whether arguments are for input, output, or both, which helps the compiler catch errors.tol is implemented as an optional argument with a default value.The code is structured into three parts:
precision_mod).optimization_mod).main.f90).optimization_mod.f90This file contains the core logic.
!> Module for defining standard floating point precision kinds.
module precision_mod
implicit none
!> Define a kind parameter for double precision reals.
integer, parameter :: dp = kind(1.0d0)
end module precision_mod
!-----------------------------------------------------------------------
!> Module containing optimization routines like the Golden Section Search.
module optimization_mod
use precision_mod
implicit none
!> Define the 'shape' of the function that our optimizer accepts.
!> It must be a function that takes one double precision real and returns
!> a double precision real.
abstract interface
function real_function_interface(x)
import :: dp
real(dp), intent(in) :: x
real(dp) :: real_function_interface
end function real_function_interface
end abstract interface
contains
!> Finds the minimum of a unimodal function using the Golden Section Search.
function golden_section_search(f, a, b, tol) result(minimum_x)
procedure(real_function_interface) :: f ! The objective function
real(dp), intent(in) :: a ! Left boundary of the interval
real(dp), intent(in) :: b ! Right boundary of the interval
real(dp), intent(in), optional :: tol ! Tolerance for the interval width
real(dp) :: minimum_x
! --- Local variables ---
real(dp), parameter :: golden_ratio = (1.0_dp + sqrt(5.0_dp)) / 2.0_dp
real(dp) :: a_loc, b_loc, c, d, fc, fd, current_tol
! Use a default tolerance if none is provided
if (present(tol)) then
current_tol = tol
else
current_tol = 1.0e-6_dp
end if
! Use local copies of the interval to modify them
a_loc = a
b_loc = b
! Calculate initial interior points
c = b_loc - (b_loc - a_loc) / golden_ratio
d = a_loc + (b_loc - a_loc) / golden_ratio
fc = f(c)
fd = f(d)
do while ((b_loc - a_loc) > current_tol)
if (fc < fd) then
! The minimum is in the left sub-interval [a, d]
b_loc = d
d = c
fd = fc
c = b_loc - (b_loc - a_loc) / golden_ratio
fc = f(c)
else
! The minimum is in the right sub-interval [c, b]
a_loc = c
c = d
fc = fd
d = a_loc + (b_loc - a_loc) / golden_ratio
fd = f(d)
end if
end do
! Return the midpoint of the final, small interval
minimum_x = (a_loc + b_loc) / 2.0_dp
end function golden_section_search
end module optimization_mod
f(x1) < f(x2)[a, x2]b becomes x2.main.f90This file contains the main program that uses the module to solve two example problems.
!> Main program to demonstrate the golden_section_search function.
program demo_gss
use precision_mod
use optimization_mod
implicit none
real(dp) :: min_x
real(dp), parameter :: pi = acos(-1.0_dp)
! --- Example 1: Minimize f(x) = (x - 2)^2 on [0, 5] ---
print '(A)', "--- Example 1: f(x) = (x - 2)^2 ---"
print '(A, F4.1, A, F4.1, A)', "Search interval: [", 0.0_dp, ", ", 5.0_dp, "]"
! Call the function using the default tolerance
min_x = golden_section_search(quadratic_func, 0.0_dp, 5.0_dp)
print '(A, F12.8)', "Estimated minimum found at: x =", min_x
print '(A, F12.8)', "Function value at minimum: f(x) =", quadratic_func(min_x)
print *
! --- Example 2: Minimize f(x) = cos(x) on [0, 6] ---
print '(A)', "--- Example 2: f(x) = cos(x) ---"
print '(A, F4.1, A, F4.1, A)', "Search interval: [", 0.0_dp, ", ", 6.0_dp, "]"
! Call the function with a specific, tighter tolerance
min_x = golden_section_search(cos_func, 0.0_dp, 6.0_dp, tol=1.0e-9_dp)
print '(A, F12.8)', "Estimated minimum found at: x =", min_x
print '(A, F12.8)', "Value of pi is approximately: ", pi
print '(A, F12.8)', "Function value at minimum: f(x) =", cos_func(min_x)
print *
contains
!> A simple quadratic function for testing. Minimum at x=2.
function quadratic_func(x)
real(dp), intent(in) :: x
real(dp) :: quadratic_func
quadratic_func = (x - 2.0_dp)**2
end function quadratic_func
!> Cosine function. Minimum in [0, 6] is at x=pi.
function cos_func(x)
real(dp), intent(in) :: x
real(dp) :: cos_func
cos_func = cos(x)
end function cos_func
end program demo_gss
Save the two code blocks into files named optimization_mod.f90 and main.f90 respectively.
Open a terminal or command prompt.
Compile the files using a Fortran compiler like gfortran. You must compile the module file first, or compile both at the same time.
# Compile both files, gfortran handles the dependency order
gfortran -o gss_demo main.f90 optimization_mod.f90
Run the executable:
./gss_demo
The output of the program will look like this:
--- Example 1: f(x) = (x - 2)^2 ---
Search interval: [ 0.0, 5.0]
Estimated minimum found at: x = 1.99999999
Function value at minimum: f(x) = 0.00000000
--- Example 2: f(x) = cos(x) ---
Search interval: [ 0.0, 6.0]
Estimated minimum found at: x = 3.14159265
Value of pi is approximately: 3.14159265
Function value at minimum: f(x) = -1.00000000