gpt4 book ai didi

c# - 为什么 C# 中的 Random 构造函数在方法末尾分配 Seed 参数?

转载 作者:行者123 更新时间:2023-11-30 13:54:15 27 4
gpt4 key购买 nike

我检查了 .Net 的随机类的源代码 here .令我惊讶的是最后一行

  public Random(int Seed) {
int ii;
int mj, mk;

//Initialize our Seed array.
//This algorithm comes from Numerical Recipes in C (2nd Ed.)
int subtraction = (Seed == Int32.MinValue) ? Int32.MaxValue : Math.Abs(Seed);
mj = MSEED - subtraction;
SeedArray[55]=mj;
mk=1;
for (int i=1; i<55; i++) { //Apparently the range [1..55] is special (Knuth) and so we're wasting the 0'th position.
ii = (21*i)%55;
SeedArray[ii]=mk;
mk = mj - mk;
if (mk<0) mk+=MBIG;
mj=SeedArray[ii];
}
for (int k=1; k<5; k++) {
for (int i=1; i<56; i++) {
SeedArray[i] -= SeedArray[1+(i+30)%55];
if (SeedArray[i]<0) SeedArray[i]+=MBIG;
}
}
inext=0;
inextp = 21;
Seed = 1;
}

方法末尾赋值的目的是什么?

最佳答案

因为 Seed 参数没有被 ref 传递并且 int 是一个值类型,所以最后一行没有任何效果。

感谢@Alex K 指出这一点,在检查了他们在 C 中的数字食谱 中采用的算法后,他们确实复制并粘贴了最后一行:

if ( * idum < 0 || iff == 0) {
Initialization.
iff = 1;
mj = labs(MSEED - labs( * idum));
Initialize ma[55] using the seed idum and the
mj %= MBIG;
large number MSEED.
ma[55] = mj;
mk = 1;
for (i = 1; i <= 54; i++) {
ii = (21 * i) % 55;
ma[ii] = mk;
mk = mj - mk;
if (mk < MZ) mk += MBIG;
mj = ma[ii];
}
for (k = 1; k <= 4; k++)
(i = 1; i <= 55; i++) {
ator.”
ma[i] -= ma[1 + (i + 30) % 55];
if (ma[i] < MZ) ma[i] += MBIG;
}
inext = 0;
inextp = 31;
* idum = 1;
}

关于c# - 为什么 C# 中的 Random 构造函数在方法末尾分配 Seed 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44699017/

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