我有一个号码,我想通常分配到15个箱子或单元格。我希望15个数字按顺序排列
示例:
待分发的数字 - 340 输出:6 9 12 16 20 24 27 30 32 32 32 30 27 24 20
...是的,我的系列并没有完美分发,但目前我正在这样做,
有更好的方法吗?因为我必须为此生成多个矩阵,而且事情不太正确...
答案 0 :(得分:1)
这是一种命中与未命中方法,用于搜索独立正态变量的随机向量,其总和落在目标和的给定容差范围内,如果是,则重新调整所有数字,以便精确地等于总和:
Function RandNorm(mu As Double, sigma As Double) As Double
'assumes that Ranomize has been called
Dim r As Double
r = Rnd()
Do While r = 0
r = Rnd()
Loop
RandNorm = Application.WorksheetFunction.Norm_Inv(r, mu, sigma)
End Function
Function RandSemiNormVect(target As Double, n As Long, mu As Double, sigma As Double, Optional tol As Double = 1) As Variant
Dim sum As Double
Dim rescale As Double
Dim v As Variant
Dim i As Long, j As Long
Randomize
ReDim v(1 To n)
For j = 1 To 10000 'for safety -- can increase if wanted
sum = 0
For i = 1 To n
v(i) = RandNorm(mu, sigma)
sum = sum + v(i)
Next i
If Abs(sum - target) < tol Then
rescale = target / sum
For i = 1 To n
v(i) = rescale * v(i)
Next i
RandSemiNormVect = v
Exit Function
End If
Next j
RandSemiNormVect = CVErr(xlErrValue)
End Function
像这样测试:
Sub test()
On Error Resume Next
Range("A1:A15").Value = Application.WorksheetFunction.Transpose(RandSemiNormVect(340, 15, 20, 3))
If Err.Number > 0 Then MsgBox "No Solution Found"
End Sub
带有这些参数的典型输出:
另一方面,如果我将标准偏差更改为1,我只是得到没有找到解决方案的消息,因为那时获得目标总和的指定容差范围内的解决方案的可能性非常小。