How does a random number generator work?

前端 未结 7 1257
终归单人心
终归单人心 2020-11-29 05:27

How do random number generator works? (for example in C/C++ Java)

How can I write my own random number generator? (for example in C/C++ Java)

7条回答
  •  渐次进展
    2020-11-29 05:37

    How I made them in the old days was by getting some value from the system that changes really rapidly, for example the system millisecond timer.

    The next thing you have to do is to apply some formula that will generate a new number from this "input" number and clip it to the range you need, eg 0..255:

    random_number = integer(formula(timer-value)) MOD 255

    That way, you have a new "random" number every time you call the function.

    An example formula function could be:
    formula(x) = ((x XOR constant) + constant2) MOD range
    XOR used to be one of my favourites.


    Update: I realize that this formula is a very bad one, it generates a pretty predictable set of numbers. Also, the system timer is too predictable as a source. So for most applications, this does not suffice. If you need better randomness, use more sources than just the system timer and better formulas to combine them.

提交回复
热议问题