Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

How does rand() work?

How does rand() work?

How does rand() work?

I am studying rand() so I tried the following:

int x;

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

Am I doing something wrong?

RE: How does rand() work?

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.

A really simple rand() has a period of 10, and generates
0 2 5 3 9 7 6 1 8 4
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


#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)


RE: How does rand() work?

Thank you!

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members! Already a Member? Login

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close