Pseudo-random number generator

前端 未结 10 710
无人及你
无人及你 2020-12-09 05:17

What is the best way to create the best pseudo-random number generator? (any language works)

相关标签:
10条回答
  • 2020-12-09 05:46

    Yikes, that can get VEEEEEERY complicated! There seem to be a number of metrics for how to measure the "randomness" of a random number generator, so it's difficult to meaure which are "best". I would start with Numerical Recipes in C (or whatever langauge you can find one for) for a few examples. I coded up my first simple one from the examples given there.

    EDIT: It's also important to start by determining how complex you need your random number generator to be. I remember a rude awakening I had in C years ago when I discovered that the default random number generator had a period somewhere around 32,767, meaning that it tended to repeat itself periodically after generating that many numbers! If you need a few dice rolls, that's fine. But not when you need to generate millions of "random" values for a simulation.

    0 讨论(0)
  • 2020-12-09 05:48

    Steal the one out of knuth seminumeric. It is high quality and simple to implement. It uses a pair of arrays, addition, and a couple of ifs. Cheap, effective, and a nice long period 2^55 if i recall correctly.

    0 讨论(0)
  • 2020-12-09 05:51

    It all depends on the application. The generator that creates the "most random" numbers might not be the fastest or most memory-efficient one, for example.

    The Mersenne Twister algorithm is a popular, fairly fast pseudo-random number generator that produces quite good results. It has a humongously large period, but also a relatively humongous state (2.5 kB). However it is not deemed good enough for cryptographic applications.

    Update: Since this answer was written, the PCG family of algorithms was published that seems to outperform existing non-cryptographic algorithms on most fronts (speed, memory, randomness and period), making it an excellent all-round choice for anything but cryptography.

    If you're doing crypto though, my answer remains: don't roll your own.

    0 讨论(0)
  • 2020-12-09 05:52

    PRNG algorithms are complicated, as is acquiring the right sources of entropy to make them work well. This is not something you want to do yourself. Every modern language has a PRNG library that will almost certainly be suitable for your use.

    xkcd random number

    0 讨论(0)
提交回复
热议问题