Problem with rand()

HI all,

I'm having a problem with rand(), in that every time I use it, it returns the same value, 1804289383.

Can anybody explain this to me, please?

Many thanks,
Ruddo...
Only call srand() once in your program.
You are probably calling it every time you call rand().
and make sure you use srand() to seed the random number generator with a different value each time you use it (like jsmith says, only once per program run).
try
srand(time(0));

This will make sure that the seed value is always unique, unless you run your program more than once per second.
Hi - thanks for the replies... I'm teaching myself C++ from a book that I've bought, and it hasn't mentioned srand() yet.

Where does it go in the program? For example, this is the example program I've copied from the book, and this is what gives me 1804289383 every time:

// Loop until a random number that is greater than 20,000.

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
int i, r;

r = rand();

for(i = 0; r <= 20000; i++)
r = rand();

cout << "Number is " << r << ". It was generated on try number " << i << ".\n";

return 0;
}

How would srand() replace rand() in that program?

Many thanks in advance... :)
srand doesn't replace rand, they both need to be used.
what rand() does is use an algorithm to generate a random number. The problem is that the algorithm is always the same, so the random number generated is always the same.
What you need is a way to "seed" that algorithm with a different number each time, so that rand() will generate a different number.
The time(0) function returns the number of seconds that has elapsed since midnight, Jan 1, 1970. Every second, the value of time(0) will change, giving you a perfect way to seed the random number generator with a different value each time you run your program.
Once and only once in your program, and before you use rand(), you should insert the line:
srand(time(0));
This will seed the generator, so that your rand() call will always give you a good approximation of a random number.

You have another problem. Your for loop doesn't test if the number is more than 20000, it generates 20000 random numbers. What you should do is use a while loop which tests the value of the random number, and only exits when the number is greater than 20000, like so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <ctime>

srand(time(0));
int number=1;  //start with a value less than 20000
int count=1;
while (number<20000)
      {
      number = rand()%maxrange;  // generate a random number
                           //between 0 and whatever max you want
      count++; //increase loop count
     }

     cout << "number is" << number;
     cout << "generated on try #: " << count;


when I run it with maxrange = 25000 I get:

23315 was generated on try :7
Last edited on
Thanks GRC... I've inserted that line as you mentioned, and the code now looks like this:

// Loop until a random number that is greater than 20,000.

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
int i, r;

srand(time(0));

for(i = 0; r <= 20000; i++)
r = rand();

cout << "Number is " << r << ". It was generated on try number " << i << ".\n";

return 0;
}


Now when I run my program, I get the result 134515049 every time, rather than a random number.

Perhaps I've inserted the srand(time(0)); in the wrong place? But I just can't seem to generate a random number... :-/
I edited my post above.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
int i, r;

srand(time(0));

for(i = 0; r <= 20000; i++) 
r = rand();

cout << "Number is " << r << ". It was generated on try number " << i << ".\n";

return 0;
}



Ive tryed it and it worked.... random number each time....
PS: If you want the number to be between 1 and X, use this for the rand();

r = rand() % MAX_RANGE + 1

Thanks all for your help!!

It's getting a bit weird now, I'm wondering whether there is something in the environment in which I'm running the program which may be affecting the output. I ran my normal rand program in Linux (and perhaps I've not got all the libraries installed?), and constantly got the same huge number.

Then I tried the same program on a Windows box using Microsoft Visual, and got the number 41 every time!

I finally copied that block of code from grcunning's post, and after removing the reference to maxrange (which, while it was in the program, I couldn't compile), I am now getting random numbers at last, so thanks :)

Additional: grcunning's program (minus the maxrange) is giving me very high random numbers, and always on the 2nd try - on Linux.

Over on the Windows PC, the same program, minus the maxrange, is giving me random numbers that all seem to be between about 23000 and 25000, but these are being returned after a different number of tries, like 6, 11, 7 etc, and not on try 2 each time like on the Linux box...

Any of you gurus care to postulate on the possible causes of such actions? :)
I'm assuming this must be something to do with something compiler-side that isn't installed properly, but I've no idea if that's true or not.

On my Windows PC I'm getting random numbers between 23000 and 31000 (so far) on different tries, yet over and over again on the Linux box I'm getting the number 134515049 on try number 0. This is the code (exactly the same code on both PCs):

// Loop until a random number that is greater than 20,000.

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
int i, r;

srand(time(0));

for(i = 0; r <= 20000; i++)
r = rand();

cout << "Number is " << r << ". It was generated on try number " << i << ".\n";

return 0;
}
The maxrange I put in there wasn't meant to be typed in literally, it was meant to be some constant that you determine.
If you want the random number to be between 0 and the maximum integer value, you can use the constant MAX_INT(you have to include <limits.h>.

The problem with this is that the number will be between 1 and 2 billion and change. This means that about 99% of the time your random number will be above 20000, so your program will rarely loop more than one time.
In our class we have always used rand()%somevalue to set a range, so I'm not sure what happens when you just call rand().
read this:
http://www.cplusplus.com/reference/clibrary/cstdlib/rand.html

anyone: how do I make the link above clickable?
Thanks again, grc, I've had a read of that page. I think I understand the whole 'random' thing better now (and am assuming there is something missing from my compiler on Linux due to the same program working on one PC but not the other).

One final thing, I notice the number produced is classed as pseudo-random. I assume that there is a type of cycle running between the lower and upper ranges when picking the random number, because when I made the range 1 - 50, and then ran the program many times in quick succession, the results were something along the lines of:
1, 6, 9, 13, 19, 26, 33, 39, 47, 49, 3, 9, 14, 23, 33, 41, 47, 1, 6.....etc etc.

Anyway - thanks all!!
rand() implements a linear congruential random number generator which has a cycle of 2^32 and generates every integer [0...2^32-1] exactly once during the cycle before repeating.

LCRNG is defined as a function

f(x) = ( f(x-1) * C1 + C2 ) mod P

where C1 and C2 are carefully chosen constants and P = 2^32.
Here x and x-1 are taken to be indices, ie, the xth random number is generated by using the x-1th random number as the seed.

Topic archived. No new replies allowed.