使用黄金分割算法求自定义连续上凸/下凸函数最小值。函数的形态应类似于下面的图形:
黄金分割算法通过多次迭代逼近最小值。如果求的是如上图(1)所示的最大值,那么在程序最后对函数值取负数即可。
以下面的问题做为例子:
对卡车(Truck)公司来说,单次运输的速度快则油耗大,但可以运送更多的货物,给出计算油耗成本与收入的公式Nprofit(净利润公式),求该公司利润最大化时的卡车速度。
编写VBA如下:
Option Explicit
Function truck(r As Double, d As Double, f As Double, w As Double, C As Boolean) As Double
'r,d,f,w-constant
Dim a As Double, b As Double, i As Integer, GR As Double, g As Double
Dim x1 As Double, x2 As Double, bestspeed As Double, max As Double
Dim fx1 As Double, fx2 As Double
GR = (Sqr(5) - 1) / 2
a = 30
b = 100
For i = 1 To 20
g = GR * (b - a)
x2 = a + g
x1 = b - g
fx1 = nprofit(r, d, f, w, x1)
fx2 = nprofit(r, d, f, w, x2)
If fx1 < fx2 Then
b = x2
Else
a = x1
End If
Next i
bestspeed = (x1 + x2) / 2
max = -(fx1 + fx2) / 2
If C = False Then truck = Format(max, "Fixed")
If C = True Then truck = Format(bestspeed, "Fixed")
End Function
其中所调用的函数代码定义如下
Function nprofit(r As Double, d As Double, f As Double, w As Double, s As Double) As Double
nprofit = f * s / ((6.12 - w / 60000) * 0.92 ^ ((s - 55) / 5)) - r * s / d
End Function
代入如下数据,包括距离、时间、油耗等参数:
执行所编写的函数,即可得到最优速度即此时的最大化净利润:
以上即使用黄金分割算法求最值的VBA实现。