Skip to content

VB.NET code for a function minimization algorithm – Golden Section Search

March 20, 2011

Here’s the Golden Section Search algorithm written in VB.NET (translated from C code):

Public Delegate Function AddressOfAFunctionWithSignatureOf(ByVal x As Double) As Double

Private Shared Sub SHFT2(ByRef a, ByRef b, ByRef c)
a = b : b = c
End Sub

Private Shared Sub SHFT3(ByRef a, ByRef b, ByRef c, ByRef d)
a = b : b = c : c = d
End Sub

Public Shared Function FindMinimumByGoldenSectionSearch(ByVal ax As Double, ByVal bx As Double, ByVal cx As Double, _
ByVal func As AddressOfAFunctionWithSignatureOf, ByVal TOL As Double, ByRef xmin As Double) As Double
Const R As Double = 0.61803399
Const C As Double = 1 - R
Dim f1, f2, x0, x1, x2, x3 As Double

x0 = ax
x3 = cx
If (Math.Abs(cx - bx) > Math.Abs(bx - ax)) Then
x1 = bx
x2 = bx + C * (cx - bx)
Else
x2 = bx
x1 = bx - C * (bx - ax)
End If

f1 = func(x1)
f2 = func(x2)

While (Math.Abs(x3 - x0) > TOL * (Math.Abs(x1) + Math.Abs(x2)))
If f2 < f1 Then
SHFT3(x0, x1, x2, R * x1 + C * x3)
SHFT2(f1, f2, func(x2))
Else
SHFT3(x3, x2, x1, R * x2 + C * x0)
SHFT2(f2, f1, func(x1))
End If
End While

If f1 < f2 Then
xmin = x1
Return f1
Else
xmin = x2
Return f2
End If
End Function

Here’s how to use. The first three parameters are x-values as starting section that we know the function does have a minimum somewhere between x1 and x3.

...
yMin=FindMinimumByGoldenSectionSearch(0.01, 0.5, 0.99,AddressOf myFuncToMinimize, 0.0001, xMin)
...
Function myFuncToMinimize(ByVal x as Double) As Double
...
End Function
Advertisements
No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: