【问题标题】:Excel UDF weighted RANDBETWEEN()Excel UDF 加权 RANDBETWEEN()
【发布时间】:2017-06-28 19:46:39
【问题描述】:

其实不是RANDBETWEEN()。我正在尝试创建一个 UDF 以返回数组中数字的索引,其中数字越大,被选择的可能性就越大。

我知道如何将概率分配给工作表中的随机数(即在概率总和上使用MATCH(),SO 上有很多东西可以解释这一点),但我想要一个 UDF,因为我要传递一个特殊的输入数组到函数中——不仅仅是一个选定的范围。

我的问题是,权重关闭,数组后面的数字比数组前面的数字更有可能返回,我看不出我的代码哪里出错了。到目前为止,这是 UDF:

Public Function PROBABLE(ParamArray inputArray() As Variant) As Long
'Takes a set of relative or absolute probabilities and ranks a random number within them
Application.Volatile (True)
Dim outputArray() As Variant
Dim scalar As Single
Dim rankNum As Single
Dim runningTot As Single

'''''
'Here I take inputArray() and convert to outputArray(), 
'which is fed into the probability code below
'''''

scalar = 1 / WorksheetFunction.Sum(outputArray)
rankNum = Rnd()
runningTot = 0

For i = 0 To UBound(outputArray)
    runningTot = runningTot + outputArray(i)
    If runningTot * scalar >= rankNum Then
        PROBABLE = i + 1
        Exit Function
    End If
Next i

End Function

该函数应查看outputArray() 中数字的相对大小,并随机选择但偏重于较大的数字。 例如。 outputArray() 的 {1,0,0,1} 应该分别分配 {50%,0%,0%,50%} 的概率但是当我测试 outputArray() 时,对于 1000 个样本和 100 次迭代,并绘制数组中第 1 项或第 4 项返回的频率,我得到了这个结果:

大约 20%:80% 的分布。绘制{1,1,1,1}(所有人都应该有平等的机会)给出了 10%:20%:30%:40% 的分布

我知道我遗漏了一些明显的东西,但我不知道是什么,有什么帮助吗?

更新

有些人想要完整的代码,这里是。

Public Function PROBABLE(ParamArray inputArray() As Variant) As Long
'Takes a set of relative or absolute probabilities and ranks a random number within them
Application.Volatile (True) 'added some dimensions up here
Dim outputArray() As Variant
Dim inElement As Variant
Dim subcell As Variant
Dim scalar As Single
Dim rankNum As Single
Dim runningTot As Single
'convert ranges to values
'creating a new array from the mixture of ranges and values in the input array
''''
'This is where I create outputArray() from inputArray()
''''
ReDim outputArray(0)
For Each inElement In inputArray
'Normal values get copied from the input UDF to an output array, ranges get split up then appended
    If TypeName(inElement) = "Range" Or TypeName(inElement) = "Variant()" Then
        For Each subcell In inElement
            outputArray(UBound(outputArray)) = subcell
            ReDim Preserve outputArray(UBound(outputArray) + 1)
        Next subcell
    'Stick the element on the end of an output array
    Else
        outputArray(UBound(outputArray)) = inElement
        ReDim Preserve outputArray(UBound(outputArray) + 1)
    End If
Next inElement
ReDim Preserve outputArray(UBound(outputArray) - 1)
''''
'End of new code, the rest is as before
''''
scalar = 1 / WorksheetFunction.Sum(outputArray)
rankNum = Rnd()
runningTot = 0

For i = 0 To UBound(outputArray)
    runningTot = runningTot + outputArray(i)
    If runningTot * scalar >= rankNum Then
        PROBABLE = i + 1
        Exit Function
    End If
Next i

End Function

开始inputArray() ???? outputArray() 部分用于标准化不同的输入法。 IE。用户可以输入值、单元格引用/范围和数组的混合,并且该函数可以应付。例如{=PROBABLE(A1,5,B1:C15,IF(ISTEXT(D1:D3),LEN(D1:D3),0))} (你明白了) 应该和 =PROBABLE(A1:A3) 一样好用。我循环遍历 inputArray() 的子元素并将它们放入我的 outputArray() 中。我相当肯定这部分代码没有任何问题。

然后为了得到我的结果,我将 UDF 复制到 A1:A1000,使用 COUNTIF(A1:A1000,1)或者代替计数 1,我为每个可能的 UDF 输出计数了 2、3、4 等 em> 并制作了一个简短的宏来重新计算工作表 100 次,每次将 countif 的结果复制到表格中以绘制图表。我不能确切地说我是怎么做到的,因为我把这一切都留在了工作中,但我会在星期一更新。

【问题讨论】:

  • 你应该把 Randomize 放在 Rnd() 行之前。
  • 有趣,似乎对我有用。您如何(以及为什么)将输入转换为输出?
  • 显示将inputArray()转换为outputArray()的代码,并描述您测试退货频率的方式。这可能会导致这样的分布。 IMO 目前的代码应该可以正常工作。
  • 刚刚运行了你的实验,只添加了一条语句:outputArray = inputArray。结果为:(50118, 0, 0, 49882)。我认为您应该检查您的实验以及复制数组的方式。这是一个单一的声明。
  • (1,1,1,1) 的结果:(25024, 25138, 24898, 24940)

标签: vba excel user-defined-functions


【解决方案1】:

试试这个:

Function Probable(v As Variant) As Long
    Application.Volatile 'remove this if you don't want a volatile function

    Dim v2 As Variant
    ReDim v2(LBound(v) To UBound(v) + 1)

    v2(LBound(v2)) = 0
    Dim i As Integer
    For i = LBound(v) To UBound(v)
        v2(i + 1) = v2(i) + v(i) / Application.Sum(v)
    Next i

    Probable = Application.WorksheetFunction.Match(Rnd(), v2, 1)
End Function

数组v 本质上就是你的outputArray。

代码采用{1,0,0,1} 之类的数组并将其转换为{0,0.5,0.5,1}(注意开头的0),此时您可以按照您的建议执行MATCH,以获得@987654328 @ 概率相等。

同样,如果您以{1,1,1,1} 开头,它将被转换为{0,0.25,0.5,0.75,1} 并以相同的概率返回1, 2, 3 or 4 中的任何一个。

另请注意:如果您将Application.Sum(v) 的值保存在一个变量中,而不是对数组v 中的每个值执行计算,您可能会更快一些。

更新
该函数现在将v 作为参数——就像你的代码一样。我还对其进行了一些调整,以便它可以处理具有任何基础的v,这意味着您也可以从工作表中运行它:例如=Probable({1,0,0,1})

【讨论】:

    【解决方案2】:

    看来我犯了一个可悲的错误。我的代码很好,我的计数不太好。我在绘图中使用SUMIF() 而不是COUNTIF(),从而导致数组中的后续对象(具有更高的 Index - 我应该计算的 UDF 的输出,但实际上求和)获得与其位置成比例的权重。

    回想起来,我认为比我聪明得多的人可能从所提供的信息中推断出这一点。我说{1,1,1,1}有一个{10%:20%:30%:40%},这是一个{1:2:3:4}的比例,这与输出的指数完全相同,推论:输出相加不计算。

    类似地,{1,0,0,1} 与 {20%:0%:0%:80%} 输出的图表,将每个百分比除以其指数 (20%/1, 80%/4) 和 Hey Presto {20%:0%:0%:20%},还是我预期的 1:1 比例。

    有些烦人但令人满意的事情 - 知道答案一直都在那里。我想这一切可能都有道德。至少这篇文章可以作为一个警告,提醒初出茅庐的 VBA 人员检查他们的算法。

    【讨论】:

      【解决方案3】:

      这是我按照您的逻辑构建的。它工作得很好,提供了不同的结果。

      Option Explicit
      Public Function TryMyRandom() As String
      
          Dim lngTotalChances         As Long
          Dim i                       As Long
          Dim previousValue           As Long
          Dim rnd                     As Long
          Dim result                  As Variant
      
          Dim varLngInputArray        As Variant
          Dim varLngInputChances      As Variant
          Dim varLngChancesReedit     As Variant
      
          varLngInputChances = Array(1, 2, 3, 4, 5)
          varLngInputArray = Array("a", "b", "c", "d", "e")
          lngTotalChances = Application.WorksheetFunction.Sum(varLngInputChances)
          rnd = Application.WorksheetFunction.RandBetween(1, lngTotalChances)
      
          ReDim varLngChancesReedit(UBound(varLngInputChances))
      
          For i = LBound(varLngInputChances) To UBound(varLngInputChances)
              varLngChancesReedit(i) = varLngInputChances(i) + previousValue
              previousValue = varLngChancesReedit(i)
      
              If rnd <= varLngChancesReedit(i) Then
                  result = varLngInputArray(i)
                  Exit For
              End If
          Next i
      
          TryMyRandom = result
      
      End Function
      
      Public Sub TestMe()
      
          Dim lng     As Long
          Dim i       As Long
          Dim dict    As Object
          Dim key     As Variant
          Dim res     As String
      
          Set dict = CreateObject("Scripting.Dictionary")
      
          For lng = 1 To 1000
      
              res = TryMyRandom
              If dict.Exists(res) Then
                  dict(res) = dict(res) + 1
              Else
                  dict(res) = 1
              End If
      
      
          Next lng
      
          For Each key In dict.Keys
              Debug.Print key & " ===> " & dict(key)
          Next
      
      
      End Sub
      

      关于您的情况,请确保数组已排序。例如,就我而言,谈论varLngInputChances。我没有看过极端情况,可能有错误。

      运行TestMe 子程序。它甚至会生成结果摘要。 如果您将变体更改为varLngInputChances = Array(1, 1, 0, 0, 1),它会给出:

      a ===> 329 b ===> 351 e ===> 320

      这是相当好的随机 :) 您可以在此处更改样本的数量: For lng = 1 To 1000,它运行得非常快。我刚刚尝试了 100,000 次测试。

      【讨论】:

        猜你喜欢
        • 2022-12-14
        • 1970-01-01
        • 2011-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多