使用 VBA 的离散函数
discrete function by using VBA
我正在尝试使用 VBA 代码创建离散函数。
它有时会起作用,但我也收到了 "Subscript of range error" 消息。有谁能知道原因吗?
Function Discrete6()
Dim value As Variant, prob As Variant, i As Integer
Dim uniform As Double, cumProb As Variant
value = Array(5, 10, 12)
prob = Array(0.2, 0.3, 0.5)
uniform = Rnd
cumProb = prob(1)
i = 1
Do Until cumProb > uniform
i = i + 1
cumProb = cumProb + prob(i)
Loop
Discrete6 = value(i)
End Function
以下修改有点脏,但它适用于您的特定情况(具有 3 个成员的数组)。
Function Discrete6()
Dim value As Variant, prob As Variant, i As Integer
Dim uniform As Double, cumProb As Variant
value = Array(5, 10, 12)
prob = Array(0.2, 0.5, 1)
uniform = Rnd
Select Case uniform
Case Is <= prob(0)
Discrete6 = value(0)
Case Is > prob(1)
Discrete6 = value(2)
Case Else
Discrete6 = value(1)
End Select
End Function
我正在尝试使用 VBA 代码创建离散函数。
它有时会起作用,但我也收到了 "Subscript of range error" 消息。有谁能知道原因吗?
Function Discrete6()
Dim value As Variant, prob As Variant, i As Integer
Dim uniform As Double, cumProb As Variant
value = Array(5, 10, 12)
prob = Array(0.2, 0.3, 0.5)
uniform = Rnd
cumProb = prob(1)
i = 1
Do Until cumProb > uniform
i = i + 1
cumProb = cumProb + prob(i)
Loop
Discrete6 = value(i)
End Function
以下修改有点脏,但它适用于您的特定情况(具有 3 个成员的数组)。
Function Discrete6()
Dim value As Variant, prob As Variant, i As Integer
Dim uniform As Double, cumProb As Variant
value = Array(5, 10, 12)
prob = Array(0.2, 0.5, 1)
uniform = Rnd
Select Case uniform
Case Is <= prob(0)
Discrete6 = value(0)
Case Is > prob(1)
Discrete6 = value(2)
Case Else
Discrete6 = value(1)
End Select
End Function