0

当我知道我的函数的根不是 0 时,我的 vba 代码一直返回值 0。

这是非常简单的代码,但我似乎无法调试它。知道这个错误可能来自哪里吗?

Option Explicit

Public Function Bisect(ByVal xlow As Double, ByVal xhigh As Double) As Double

Dim i As Integer
Dim xmid As Double

xmid = (xlow + xhigh) / 2

For i = 1 To 100

If f(xlow) * f(xmid) < 0 Then
    xhigh = xmid
    xmid = (xlow + xhigh) / 2
Else
    xlow = xmid
    xmid = (xlow + xhigh) / 2
End If

Next i

Bisect = xmid

End Function

Function f(ByVal x As Double, Optional ByRef inputArray As Range) As Variant

Dim ca0 As Double
Dim v0 As Double
Dim k As Double
Dim e As Double
Dim ac As Double
Dim L As Double

inputArray(2, 2) = ca0
inputArray(3, 2) = v0
inputArray(4, 2) = k
inputArray(5, 2) = e
inputArray(6, 2) = ac
inputArray(7, 2) = L

f(x) = (v0 / (k * ca0 * ac)) * ((2 * e * (1 + e) * Log(1 - x)) + (e ^ 2 * x) + (((1 + e) ^ 2 * x) / (1 - x))) - L

End Function
4

2 回答 2

0
' i Think you want to take those constant values from cells presentin the sheet

Function f(ByVal x As Double) As Variant


Dim inputArray As Range

Dim ca0 As Double
Dim v0 As Double
Dim k As Double
Dim e As Double
Dim ac As Double
Dim L As Double

' i Think you want to take values from cells in the sheet

ca0 = ActiveSheet.Cells(2, 2).Value
v0 = ActiveSheet.Cells(3, 2).Value
k = ActiveSheet.Cells(4, 2).Value
e = ActiveSheet.Cells(5, 2).Value
ac = ActiveSheet.Cells(6, 2).Value
L = ActiveSheet.Cells(7, 2).Value
于 2015-10-27T07:48:55.580 回答
0

可能是您尝试为 inputarray 分配空变量吗?

在我看来应该是:

ca0 = inputArray(2, 2)
v0 = inputArray(3, 2) 

等等。

我正在猜测

f(x) = (v0 / (k * ca0 * ac)) * ((2 * e * (1 + e) * Log(1 - x)) + (e ^ 2 * x) + (((1 + e) ^ 2 * x) / (1 - x))) - L

应该

f = (v0 / (k * ca0 * ac)) * ((2 * e * (1 + e) * Log(1 - x)) + (e ^ 2 * x) + (((1 + e) ^ 2 * x) / (1 - x))) - L
于 2015-10-27T07:41:30.880 回答