29

What is a seed in terms of generating a random number?

I need to generate hundreds to thousands of random numbers, I have read a lot about using a "seed". What is a seed? Is a seed where the random numbers start from? For example if I set my seed to be 5 will it generate numbers from 5 to whatever my limit is? So it will never give me 3 for example.

I am using C++, so if you provide any examples it'd be nice if it was in C++.

Thanks!

SirRupertIII
  • 12,324
  • 20
  • 72
  • 121

2 Answers2

38

What is normally called a random number sequence in reality is a "pseudo-random" number sequence because the values are computed using a deterministic algorithm and probability plays no real role.

The "seed" is a starting point for the sequence and the guarantee is that if you start from the same seed you will get the same sequence of numbers. This is very useful for example for debugging (when you are looking for an error in a program you need to be able to reproduce the problem and study it, a non-deterministic program would be much harder to debug because every run would be different).

If you need just a random sequence of numbers and don't need to reproduce it then simply use current time as seed... for example with:

srand(time(NULL));
6502
  • 112,025
  • 15
  • 165
  • 265
  • Well, yes, `srand` to seed `rand()`. But the rich new random number generators in TR1 (okay, not so new) and in C++11 all have their own mechanics for seeding, and `srand` is not involved. – Pete Becker Feb 16 '13 at 21:43
  • @PeteBecker: my wild guess is that for what the OP needs `srand/rand` is more than enough. – 6502 Feb 17 '13 at 00:31
  • Yes, probably. Still, seeding isn't just about `srand`. `` – Pete Becker Feb 17 '13 at 13:00
  • @6502: why you passed null as an argument to time() function? Can I pass anything other than NULL? – Destructor Oct 17 '15 at 05:17
  • 1
    @PravasiMeet: `time` for historical reasons dating back to pre-standard C accepts a pointer where to store the `time_t` value that is also returned by the function. Normally modern code never needs to pass anything but `NULL` when calling `time`. – 6502 Oct 17 '15 at 06:19
  • This is the only answer that I can understand – Spring Jan 31 '23 at 05:40
4

So, let's put it this way:

if you and your friend set the seed equals to the same number, by then you and your friend will get the same random numbers. So, if all of us write this simple program:

#include<iostream>
using namespace std;
void main () {
    srand(0);
    for (int i=0; i<3; i++){
        int x = rand()%11;          //range between 0 and 10
        cout<<x<<endl;
    }
}

We all will get the same random numbers which are (5, 8, 8).

And if you want to get different number each time, you can use srand(time())

Anwarvic
  • 12,156
  • 4
  • 49
  • 69