gpt4 book ai didi

C# 我做的 "Bays & Durham Randomization by Shuffling"正确吗?

转载 作者:行者123 更新时间:2023-11-30 12:19:34 25 4
gpt4 key购买 nike

我尝试使用“Bays & Durham Randomization by Shuffling”算法即兴创作一个随机数生成器。我按照在线教程制作了这段代码:

 public int[] GenerateRandomSequence_Improved(int n, int min, int max)
{
int[] seq = new int[n];
for(int i = 0; i < n; i++)
{
int rand = GenerateNextRandomNumber(min, max);

rand = min + rand % (max + 1 - min);
seq[i] = rand;
}
return seq;
}

我想知道我做的对不对..

编辑:这是 GenerateNextRandomNumber 方法的代码

public int GenerateNextRandomNumber(int min, int max)
{
return cSharpRNG.Next(min,max);
}

最佳答案

根据 Knuth TAOCP Vol. 2 页34 算法B,正确的算法如下,

public class BaysDurham
{
private readonly int[] t;
private int y; // auxiliary variable

// Knuth TAOCP Vol. 2 p. 34 Algorithm B

public BaysDurham(int k)
{
t = new int[k];

for (int i = 0; i < k; i++)
{
t[i] = rand.Next();
}

y = rand.Next();
}

public int Next()
{
var i = (int)((t.Length * (long) y) / int.MaxValue); // mitigates the bias
y = t[i];
t[i] = rand.Next();
return y;
}

private readonly Random rand = new Random();
}

我让您调整输出范围,但只知道您使用模数的公式会引入显着偏差并使分布不均匀 please look at this .

关于C# 我做的 "Bays & Durham Randomization by Shuffling"正确吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56408054/

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