gpt4 book ai didi

VBA 随机数以固定间隔产生重复序列

转载 作者:行者123 更新时间:2023-12-04 21:01:07 26 4
gpt4 key购买 nike

此代码应该在 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

最佳答案

For some reason I am only able to produce a unique sequence of length 5842, and then it repeats. But, and this is the strangest part, each time I run the code, the sequence starts in a different place



这是设计使然并且众所周知 - 这就是为什么数字生成被标记为伪随机而不是随机的原因。

顺便说一下,我注意到您将两个值相乘。这可能不是一个好主意 - 如前所述 here .

在您的函数中,您可以尝试替换 RndRndDbl :
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#

生成的值仍然不是真正的随机值,但不应采用重复序列的形式。

关于VBA 随机数以固定间隔产生重复序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52172582/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com