Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How does rand() work? 1

Status
Not open for further replies.

Rmcta

Technical User
Nov 1, 2002
478
0
0
US
I am studying rand() so I tried the following:

int x;
x=rand();

I do a printf of x and every time I run it, the number is always 41????

Am I doing something wrong?
 
rand() isn't random at all - it's just a mathematical function which produces a sequence of numbers which are superficially random. If you know the algorithm, they're not random at all.

Here is one typical implementation

Call rand() often enough, you will start repeating the same sequence over again. This is known as the period of the random number generator. Really good algorithms like the Mersenne Twister have huge periods.

The only thing you can change is the seed, which changes your start position in the sequence.

Example
A really simple rand() has a period of 10, and generates
[tt]0 2 5 3 9 7 6 1 8 4[/tt]
If the seed is 1 say, then it will always start by giving you the answer 0, followed by 2 then 5 etc
If you change the seed to 4 say, then you'll get 3, 9, 7 etc

In your C code, you typically start your program with
Code:
#include <stdlib.h>
#include <time.h>
int main ( ) {
  srand( (unsigned)time(NULL) );
}
So long as you don't run your program twice in the same second, you'll get different answers from rand(), because you'll keep changing the start position (seed value)

--
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top