我在这个双变量优化程序中遇到溢出问题

时间:2012-12-20 00:32:35

标签: vba excel-vba excel-2010 excel

首先,这是我到目前为止所做的:

Option Explicit

Dim y As Variant
Dim yforx As Variant
Dim yfork As Variant
Dim ynew As Variant
Dim ymin As Variant
Dim x As Variant
Dim xmin As Variant
Dim k As Variant
Dim kmin As Variant
Dim s As Variant
Dim Z As Variant
Dim Track As Variant


Sub PracticeProgram()

'Selects the right sheet
Sheets("PracticeProgram").Select

'y = k ^ 2 * (x ^ 2 + 2 * x * k - 6) / (x + k) ^ 2

'these are the bounds we are stepping through
Track = 0
x = 1
xmin = 1
k = 1
kmin = 1
y = 100000000
yforx = 100000
yfork = 1000000000

Do
    y = 100000000
    For x = 0 To 1000 Step 0.1
        ynew = kmin ^ 2 * (x ^ 2 + 2 * x * kmin - 6) / (x + kmin) ^ 2

        'This checks the new y-value against an absurdly high y-value we know is wrong. if it is less than this y-value, we keep the x-value that corresponds with it.
        If ynew < y Then
            xmin = x
            y = ynew
            yforx = y
            xmin = Application.Evaluate("=Round(" & xmin & ", 3)")
        Else
        End If

    Next
  MsgBox (yforx)


    For k = 0 To 1000 Step 0.1
        y = k ^ 2 * (xmin ^ 2 + 2 * xmin * k - 6) / (xmin + k) ^ 2
        If ynew < y Then
            kmin = k
            y = ynew
            yfork = y
            kmin = Application.Evaluate("=Round(" & kmin & ",3)")
        Else
        End If
        Next

    MsgBox (yfork)

Loop Until (Abs(yforx - yfork) < 10)

End Sub

该程序应该找到x和k的值,以便最小化y的值。这是一个使用相同概念的更复杂程序的实践。在我的实际程序中,无论如何,y,k和x都将大于零,但由于很难想到一个简单的方程,其结果将是抛物线开放的形状,我决定允许否定答案这个练习计划。

基本上,它应该在找到x和k的理想值的方程之间来回反转,直到最后它使用x和k的理想答案得到y的最小答案。我不确定实际的答案是什么,所以我让它在10的范围内停止。如果它有效,我会把它缩小,但我不希望程序永远存在,以防万一

我的问题:我一直遇到溢出错误!我试图将xmin和kmin的值四舍五入到三位数之后,但似乎并没有帮助。我用错了吗?有人可以帮助我让这个程序工作吗?

1 个答案:

答案 0 :(得分:3)

你正在做零除法。 xmin = 0k = 0(xmin + k) ^ 2 = 0。 (我不确定为什么不报告除零。)

建议:使用Locals窗格查看局部变量的值。您还可以使用Watch窗格查看要监控的表达式的值。