Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

srand producing the same sequence of random numbers

by e_c (Initiate)
on Oct 12, 2010 at 01:00 UTC ( [id://864719]=perlquestion: print w/replies, xml ) Need Help??

e_c has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I have used: 12892579 12581113 11469568 to see the random number generator using srand and am getting the same sequence of numbers. Is this a known bug? What is the best way of using srand? TIA eddiec :-)
  • Comment on srand producing the same sequence of random numbers

Replies are listed 'Best First'.
Re: srand producing the same sequence of random numbers
by merlyn (Sage) on Oct 12, 2010 at 01:12 UTC
    The proper way to use srand is to ignore srand, unless you need a repeatable start point, or a cryptographically strong start point (in which case, you're probably not using rand() either). The random number generator is fairly seeded on each new run.

    -- Randal L. Schwartz, Perl hacker

    The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119.

Re: srand producing the same sequence of random numbers
by ww (Archbishop) on Oct 12, 2010 at 01:19 UTC

    Do you mean you fed those numbers to srand something like this:

    ~$ perl -wle 'srand(12345); for (1..3) {print rand(5);}' 1.12664256398149 4.59591534266778 1.03420626624091 ~$
    and got the same output for each seed?

    Two obvious possibilities:

    1. Your installation is broken
    2. your code didn't use the seed properly

    Of course, there are countless other possibilities depending on just what you actually did.

    But we can't see your code. And since we can't see it, it's really hard to know how to help you fix your problem. Maybe you should post the code (and read On asking for help and How do I post a question effectively? and maybe even I know what I mean. Why don't you?.

    In fact, the only question I can answer with any confidence is the "bug?" question... and the answer to that is "no."

    As to the "best way" to use srand? Well, it depends on what you're going to do with its output. But (sigh!), you didn't tell us that either. (However, for that, you might want to read perldoc -f srand whence this snippet comes:

    You can call srand($seed) with the same $seed to reproduce the same sequence from rand(), but this is usually reserved for generating predictable results for testing or debugging. Otherwise, don't call srand() more than once in your program.
Re: srand producing the same sequence of random numbers
by sundialsvc4 (Abbot) on Oct 12, 2010 at 03:52 UTC

    AFAIK, the only purpose for srand() is to be able to obtain a repeatable set of “random” numbers, e.g. for certain esoteric statistical sampling purposes or some similar special purpose. The intended behavior is exactly what you saw:   after re-seeding, the pseudo-random sequence repeats.

    The random number generator does not need to be re-seeded, ever, in normal practice.

    The standard random number generator is not suitable for cryptographic purposes.

      The random number generator does not need to be re-seeded, ever, in normal practice.

      Every interpreter needs to be seeded. Perl will do that automatically, except when the interpreter is cloned by fork.

      $ perl -e' rand(10); if (my $pid = fork()) { waitpid($pid, 0); } local ($,, $\) = (", ", "\n"); print map int(rand(10)), 1..10; ' 8, 3, 9, 8, 8, 2, 3, 8, 4, 8 8, 3, 9, 8, 8, 2, 3, 8, 4, 8
Re: srand producing the same sequence of random numbers
by ikegami (Patriarch) on Oct 12, 2010 at 02:12 UTC

    ActivePerl on Windows:

    >perl -wle"for (12892579, 12581113, 11469568) { srand($_); print rand( +10) for 1..3; print ''; }" 8.4423828125 8.1201171875 0.3485107421875 8.04290771484375 1.88720703125 7.26837158203125 0.30426025390625 3.8690185546875 3.51715087890625

    Linux:

    $ perl -wle'for (12892579, 12581113, 11469568) { srand($_); print rand +(10) for 1..3; print ""; }' 7.28681520399736 9.72810111099051 8.4866120390701 4.16810684212582 9.99273993631022 1.63078077641455 4.64624992645444 9.91696268643381 6.90260832469118

    What output do you get? What platform? (perl -V, that's an uppercase "V")

Re: srand producing the same sequence of random numbers
by dsheroh (Monsignor) on Oct 12, 2010 at 12:22 UTC
    You have greatly misunderstood the purpose of srand. This is not a bug. If you repeatedly call srand with the same seed, then you will get the same sequence of pseudorandom numbers from rand each time. That's what srand does.

    If you want a different set of pseudorandom numbers each time, then forget that srand even exists. The first call to rand will automatically seed the PRNG with a value based on the system clock, which will get you close enough to actual randomness for most practical purposes.

      This is the answer the OP is looking for.

      Seeding a random number generator means giving it a number to start from - all "random number generators" that are not hooked to an actual source of entropy (like atomic decay, thermal noise, or the like) are simply doing calculations that return a sequence of numbers whose distribution looks random "enough". Knuth spends an entire volume of different definitions of "enough"; it's a very deep (and interesting) subject. (Most random number generators use a "linear congruential" calculation that essentially uses two largish numbers that are relatively prime to one another; the seed is multiplied by one, and then the product is reduced modulo the other. This has the advantage that it's a fairly fast operation (one multiply and one divide), and yields fairly good results.)

      Seed functions exist to allow you to reproduce a given random sequence; this can be very useful when you're trying to test a module which contains a random component, as the behavior is still "random" (that is driven by the output of the rand() function) but at the same time completely predictable (since the sequence of numbers coming from rand() will be exactly the same every time for the same seed).

Re: srand producing the same sequence of random numbers
by mjscott2702 (Pilgrim) on Oct 12, 2010 at 08:24 UTC
    The question here, I believe, is not related to the nature of (pseudo) random distributions - just why the same initial sequence gets displayed?

    Well, as stated by another responder, that's one of the uses of srand() - from the perldoc -f srand output:

    You can call srand($seed) with the same $seed to reproduce the same sequence from rand(), but this is usually reserved for generating predictable results for testing or debugging. Otherwise, don't call srand() more than once in your program.

    Since srand is implicitly called on the first rand() call, there is no need to even call srand. Unless you need to :)

      As far as I am aware, this behavior is the only (practical) purpose for the existence of srand().

      Certain statistical tests require that a (pseudo-)random sample be taken from a population, then at some future point, another sample is taken which examines the same elements.   One way to do this, of course, would be to store the random sequence, but that can be memory-intensive.   Hence, srand().   First, you obtain a random number in the usual way.   Then, you use srand() to establish that (randomly chosen) number as the new “seed.”   Now, you can easily produce an arbitrarily long pseudo-random number sequence that can be repeated perfectly, just by re-assigning the seed.

      Because this is Perl, “TMTOWTDI.™”   Perl has many pseudo-random number generator packages available.

      As far as I am aware, this behavior is the only (practical) purpose for the existence of srand().

      Certain statistical tests require that a (pseudo-)random sample be taken from a population, then at some future point, another sample is taken which examines the same elements.   One way to do this, of course, would be to store the random sequence, but that can be memory-intensive.   Hence, srand().   First, you obtain a random number in the usual way.   Then, you use srand() to establish that (randomly chosen) number as the new “seed.”   Now, you can easily produce an arbitrarily long pseudo-random number sequence that can be repeated perfectly, just by re-assigning the seed.

      Because this is Perl, &ldquolTMTOWTDI.™”   Perl has many pseudo-random number generator packages available.

Re: srand producing the same sequence of random numbers
by aquarium (Curate) on Oct 12, 2010 at 03:21 UTC
    if you're not after a repeatable set, seed it every time with timer value. that's pretty close to something resembling a random set of numbers.
    btw there's only ever a theoretically possible set of true random numbers, and nothing like it in programming or life/nature. and the harder mathematicians and/or programmers strive to get to truly random number sets, the more they approach a truly contrived/artificial set.
    just a matter of how random you want your set of numbers to appear. seeding with timer seconds or milliseconds value works for me on most occasions.
    the hardest line to type correctly is: stty erase ^H
      It is a philosophical question whether any true randomness exists. Even at the quantum level there is some debate (see Einstein's famous quote "I, at any rate, am convinced that He does not throw dice.").

      Anyhow, to get some real life random (in the sense of unpredictable at the present state of science) figures, see http://www.random.org/

      CountZero

      A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

        It is a philosophical question whether any true randomness exists. Even at the quantum level there is some debate

        There is some debate, but the overwhelming majority of the scientific community has accepted that there is true randomness.

        (see Einstein's famous quote "I, at any rate, am convinced that He does not throw dice.")

        Smart as he was, Einstein didn't offer any other explanation for things that quantum mechanics explains.

        I think his rejection was based on the old mechanistic view of the world, which assumed that given enough information and the correct formulas, it is possible to exactly predict everything.

        There is a saying that major scientific theories don't get accepted by convincing the opponents, but that the opponents die out in the end. That's what happened here too.

        Perl 6 - links to (nearly) everything that is Perl 6.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://864719]
Approved by ww
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (3)
As of 2024-04-20 04:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found