在.net中生成随机数而不使用任何内置函数
本文关键字:任何 内置 函数 net 随机数 | 更新日期: 2023-09-27 18:09:47
我想知道每种编程语言中的随机函数是如何工作的,所以我想自己生成一个数字,即我不想使用任何内置的类或函数。
为了简单性和速度,很难击败Xorshift随机数生成器。它是否产生一个好的发行是另一个问题。
c#中的一个例子:http://www.codeproject.com/KB/cs/fastrandom.aspx
不同的语言和环境使用不同的随机数生成器。正如其他人指出的,有很多方法可以生成伪随机数。
参见c#正常随机数和其他类似的堆栈溢出问题
如果您对它的工作原理感到好奇,您可以从Wikipedia:随机数生成和随机数生成器列表开始。第二个链接会给你一些流行的算法列表(比如Mersenne Twister),你可以自己实现。
你也可以反编译System。随机使用。net Reflector,并将给定的算法与。net本地实现的算法进行比较
D. Knuth的《计算机编程艺术》中有一章是关于随机数及其生成的
正如其他人所评论的那样,您确实需要依赖框架功能来实现这一点。如果这是出于学术目的或纯粹的兴趣,那么有许多易于实现的RNG算法。一种是进位乘(MWC)算法,它可以在c#中轻松实现:
public class RNG
{
// Seeds
static uint m_w = 362436069; /* must not be zero */
static uint m_z = 521288629; /* must not be zero */
public int NextRandom()
{
m_z = 36969 * (m_z & 65535) + (m_z >> 16);
m_w = 18000 * (m_w & 65535) + (m_w >> 16);
return (int)((m_z << 16) + m_w);
}
}
有关MWC的详细信息,请参见http://www.bobwheeler.com/statistics/Password/MarsagliaPost.txt
不使用Random()方法生成随机数
using System;
public class GenerateRandom
{
private int max;
private int last;
static void Main(string[] args)
{
GenerateRandom rand = new GenerateRandom(10);
for (int i = 0; i < 25; i++)
{
Console.WriteLine(rand.nextInt());
}
}
// constructor that takes the max int
public GenerateRandom(int max)
{
this.max = max;
DateTime dt = DateTime.Now;//getting current DataTime
int ms = dt.Millisecond;//getting date in millisecond
last = (int) (ms % max);
}
// Note that the result can not be bigger then 32749
public int nextInt()
{
last = (last * 32719 + 3) % 32749;//this value is set as per our requirement(i.e, these is not a static value
return last % max;
}
}