找到函数的最小点

时间:2015-10-31 13:34:47

标签: vb.net minimum

如果我有一条凸曲线,并想使用for或while循环找到最小点(x,y)。我在考虑像

这样的东西
dim y as double
dim LastY as double = 0
for i = 0 to a large number
  y=computefunction(i)
  if lasty > y then exit for
next

我怎么能达到最低点? (x始终> 0且为整数)

2 个答案:

答案 0 :(得分:1)

非常接近

你只需要

realm.write()

如果此代码需要很长时间才能运行,您可以很容易地将其转换为使用parallel.For的多线程循环 - 例如

dim y as double
dim smallestY as double = computefunction(0)
for i = 0 to aLargeNumber as integer
    y=computefunction(i)
    if smallestY > y then smallestY=y
next
'now that the loop has finished, smallestY should contain the lowest value of Y

这会自动为循环的每次迭代创建单独的线程。

答案 1 :(得分:1)

对于样本函数:

y = 0.01 * (x - 50) ^ 2 - 5

properly written like this

enter image description here

x = 50y = -5的最低值为mathematically obvious,您可verify with google

enter image description here

在VB.NET控制台应用程序converted from python下面,找到x=50.0000703584199, y=-4.9999999999505的最小值,这对于0.0001的指定容差是正确的:

Module Module1

  Sub Main()
    Dim result As Double = GoldenSectionSearch(AddressOf ComputeFunction, 0, 100)
    Dim resultString As String = "x=" & result.ToString + ", y=" & ComputeFunction(result).ToString
    Console.WriteLine(resultString) 'prints x=50.0000703584199, y=-4.9999999999505
  End Sub

  Function GoldenSectionSearch(f As Func(Of Double, Double), xStart As Double, xEnd As Double, Optional tol As Double = 0.0001) As Double
    Dim gr As Double = (Math.Sqrt(5) - 1) / 2

    Dim c As Double = xEnd - gr * (xEnd - xStart)
    Dim d As Double = xStart + gr * (xEnd - xStart)

    While Math.Abs(c - d) > tol
      Dim fc As Double = f(c)
      Dim fd As Double = f(d)

      If fc < fd Then
        xEnd = d
        d = c
        c = xEnd - gr * (xEnd - xStart)
      Else
        xStart = c
        c = d
        d = xStart + gr * (xEnd - xStart)
      End If
    End While

    Return (xEnd + xStart) / 2
  End Function

  Function ComputeFunction(x As Double)
    Return 0.01 * (x - 50) ^ 2 - 5
  End Function

End Module

旁注:您最初尝试找到最小值是假设函数是离散的,这在现实生活中是不太可能的。使用简单的for循环得到的是一个非常粗略的估计,并且很长时间才能找到它,因为线性搜索在其他方法中效率最低。