2

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

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 的值四舍五入到小数点后三位,但这似乎没有帮助。我用错了吗?有人可以帮我让这个程序正常工作吗?

4

1 回答 1

3

您正在除以零。xmin = 0, k = 0, (xmin + k) ^ 2 = 0. (我不确定为什么它不报告除以零。)

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

于 2012-12-20T01:01:44.120 回答