Crossplatform random number generator

2019-03-15 05:16发布

When you need to be able to generate a random number from a seed, and guarantee it be the same number across different versions of the .NET Framework and Mono Framework, as-well as across different architectures (x86, x64), what do you do?

I'm presently considering storing millions of random bytes in a file for use as a temporary solution to this problem, but I think there's probably a better way (hopefully not too much more complicated).

标签: c# random
3条回答
Anthone
2楼-- · 2019-03-15 05:47

If you need a truly portable implementation, the best option would probably be to just use a custom random number generator, such as this Mersenne Twister implementation or Colin Green's Fast Random Number Generator. By controlling the implementation, you can guarantee that you'll get the same results given the same seed on any platform.

查看更多
在下西门庆
3楼-- · 2019-03-15 05:55

There's also the Troschuetz.Random library available through NuGet which provides several "standard" randomization methods which are presumably available on other platforms as well:

Fully managed library providing various random number generators and distributions. More precisely, this library offers 7 generators (ALF, MT19937, Standard, XorShift128, NR3, NR3Q1, NR3Q2), 6 discrete distributions (Bernoulli, Binomial, Categorical, DiscreteUniform, Geometric, Poisson) and 21 continuous distributions (like Normal, Exponential, ChiSquare, Beta, and so on); moreover, it offers a random class similar to the one Python offers (TRandom).

All the hard work behind this library was done by Stefan Troschütz and optimized within this .NET package by Alessio Parma.

查看更多
虎瘦雄心在
4楼-- · 2019-03-15 05:59

Got following code from Wiki: http://en.wikipedia.org/wiki/Random_number_generation

m_w = <choose-initializer>;    /* must not be zero */
m_z = <choose-initializer>;    /* must not be zero */

uint get_random()
{
    m_z = 36969 * (m_z & 65535) + (m_z >> 16);
    m_w = 18000 * (m_w & 65535) + (m_w >> 16);
    return (m_z << 16) + m_w;  /* 32-bit result */
}

This should be what you need: http://en.wikipedia.org/wiki/Linear_congruential_generator

查看更多
登录 后发表回答