What is a seed in terms of generating a random number? [duplicate]
Asked Answered
C

2

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!

Cattleman answered 16/2, 2013 at 20:6 Comment(0)
S
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));
Stamm answered 16/2, 2013 at 20:12 Comment(6)
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.Drusilladrusus
@PeteBecker: my wild guess is that for what the OP needs srand/rand is more than enough.Stamm
Yes, probably. Still, seeding isn't just about srand. <g>Drusilladrusus
@6502: why you passed null as an argument to time() function? Can I pass anything other than NULL?Misapprehend
@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.Stamm
This is the only answer that I can understandSpectroscope
L
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())

Lagasse answered 11/4, 2016 at 12:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.