VBA寻根槽对分法
当我知道函数的根不是0时,我的vba代码会不断返回值0 这是非常简单的代码,但我似乎无法调试它。知道这个错误可能来自哪里吗VBA寻根槽对分法,vba,excel,bisection,Vba,Excel,Bisection,当我知道函数的根不是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)
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
选项显式
公共函数对分(ByVal xlow为双精度,ByVal xhigh为双精度)为双精度
作为整数的Dim i
Dim xmid为双精度
xmid=(xlow+xhigh)/2
对于i=1到100
如果f(xlow)*f(xmid)<0,则
xhigh=xmid
xmid=(xlow+xhigh)/2
其他的
xlow=xmid
xmid=(xlow+xhigh)/2
如果结束
接下来我
对分=xmid
端函数
函数f(ByVal x作为双精度函数,可选ByRef inputArray作为范围)作为变量
暗淡的ca0为双色
尺寸v0为双精度
把k调成双色
把e调成双色
将交流调暗为双
我是双人的
输入阵列(2,2)=ca0
输入阵列(3,2)=v0
输入阵列(4,2)=k
输入阵列(5,2)=e
输入阵列(6,2)=交流
输入阵列(7,2)=L
f(x)=(v0/(k*ca0*ac))*((2*e*(1+e)*对数(1-x))+(e^2*x)+((1+e^2*x)/(1-x))-L
端函数
是否可能是您试图用空变量分配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
' 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