Excel VBA强大的随机数发生器

我会尽量保持这一点尽可能基本和重点。

基本上,我有一定的范围的数字相关的权重/概率。 例如 :

0:10%

1:50%

2:15%

3:25%

这然后转化为累积概率:

0:10%

1:60%

2:75%

3:100%

在VBA中使用统一的RNG,程序会生成0到1之间的数字,或者设置的任何次数限制。 使用与前面的示例相同的值,但只生成大于60%(<= 100%)的数字,则会导致数字在0.6 – 1.0之间。

这是我卡住的地方。 我需要将这些随机数字非常有效地转换成它们的“对应值”。

所有这些都存储在VBAvariables中,不用说,我不想为每种情况写一个Select Case,因为它们实际上是120个不同的variables和权重。

到目前为止,这是我必须生成这些数字:

RandomNumber = LowerLimit + Rnd() * (1 - LowerLimit) 

感谢您的帮助! 如果我错过了一个正在讨论这个特定问题的post,请随时引荐我,但是我确实没有find与相应的随机数有关的任何内容。

将以下function放入公共模块。 你可以这样称呼它: mynumber = WeightedRnd(Array(0, 1, 2, 3), Array(0.1, 0.5, 0.15, 0.25))

 Public Function WeightedRnd(values As Variant, weights As Variant) As Double 'First, calculate the cumulative weights Dim cumulativeWeight As Double For i = 0 To UBound(weights) weights(i) = weights(i) + cumulativeWeight cumulativeWeight = weights(i) Next 'Next, generate our random number Dim randomNumber As Double randomNumber = Rnd() 'Finally, figure out which "bucket" it falls into For i = 0 To UBound(weights) If randomNumber <= weights(i) Then WeightedRnd = values(i) Exit Function End If Next End Function