Why do I always get the same sequence of random numbers with rand()?

前端 未结 12 2436
忘了有多久
忘了有多久 2020-11-21 06:06

This is the first time I\'m trying random numbers with C (I miss C#). Here is my code:

int i, j = 0;
for(i = 0; i <= 10; i++) {
    j = rand();
    printf         


        
12条回答
  •  攒了一身酷
    2020-11-21 06:30

    If I remember the quote from Knuth's seminal work "The Art of Computer Programming" at the beginning of the chapter on Random Number Generation, it goes like this:

    "Anyone who attempts to generate random numbers by mathematical means is, technically speaking, in a state of sin".

    Simply put, the stock random number generators are algorithms, mathematical and 100% predictable. This is actually a good thing in a lot of situations, where a repeatable sequence of "random" numbers is desirable - for example for certain statistical exercises, where you don't want the "wobble" in results that truly random data introduces thanks to clustering effects.

    Although grabbing bits of "random" data from the computer's hardware is a popular second alternative, it's not truly random either - although the more complex the operating environment, the more possibilities for randomness - or at least unpredictability.

    Truly random data generators tend to look to outside sources. Radioactive decay is a favorite, as is the behavior of quasars. Anything whose roots are in quantum effects is effectively random - much to Einstein's annoyance.

提交回复
热议问题