该代码应在VBA中生成10,000个随机数的序列。由于某种原因,我只能生成长度为5842的唯一序列,然后重复该序列。但是,这是最奇怪的部分,每次我运行代码时,序列都在不同的地方开始。例如,在一次运行中,元素2660之后的元素与元素8502之后的元素相同(8502-2660 = 5842)。下一次运行,我得到一个重复元素3704和9546(9546-3704 = 5842)的序列。等等。
Function NormRand() As Double
' NormRand returns a randomly distributed drawing from a
' standard normal distribution i.e. one with:
' Average = 0 and Standard Deviation = 1.0
Dim fac As Double, rsq As Double, v1 As Double, v2 As Double
Static flag As Boolean, gset As Double
' Each pass through the calculation of the routine produces
' two normally-distributed deviates, so we only need to do
' the calculations every other call. So we set the flag
' variable (to true) if gset contains a spare NormRand value.
If flag Then
NormRand = gset
' Force calculation next time.
flag = False
Else
' Don't have anything saved so need to find a pair of values
' First generate a co-ordinate pair within the unit circle:
Do
v1 = 2 * Rnd - 1#
v2 = 2 * Rnd - 1#
rsq = v1 * v1 + v2 * v2
Loop Until rsq <= 1#
' Do the Math:
fac = Sqr(-2# * Log(rsq) / rsq)
' Return one of the values and save the other (gset) for next time:
NormRand = v2 * fac
gset = v1 * fac
flag = True
End If
End Function
答案 0 :(得分:2)
由于某种原因,我只能产生一个唯一的长度序列 5842,然后重复。但是,这是最奇怪的部分 当我运行代码时,序列从另一个位置开始
这是设计使然并且众所周知的-这就是为什么数字生成被标记为伪随机而不是随机的原因。
顺便说一句,我注意到您正在将两个值相乘。如here所述,这可能不是一个好主意。
在您的函数中,您可以尝试将Rnd
替换为RndDbl
:
Public Function RndDbl(Optional ByRef Number As Single) As Double
' Exponent to shift the significant digits of a single to
' the least significant digits of a double.
Const Exponent As Long = 7
Dim Value As Double
' Generate two values like:
' 0.1851513
' 0.000000072890967130661
' and add these.
Value = CDbl(Rnd(Number)) + CDbl(Rnd(Number) * 10 ^ -Exponent)
RndDbl = Value
End Function
,然后通过调用Timer
来修改代码以包含动态种子:
Do
v1 = 2 * RndDbl(-Timer) - 1#
v2 = 2 * RndDbl(-Timer) - 1#
rsq = v1 + v2
Loop Until rsq <= 1#
生成的值仍然不是真正的随机值,但不应采用重复序列的形式。