rand() generating numbers outside of expected range

Why does this code generate values outside of the expected range of 33 to 126?

1
2
3
4
5
6
7
8
9
	int vi;
        int i;
	for (i = 0; i < 20; i++)
	{
		srand(time(0));
		v1 = rand() % 126 + 33;
		cout << v1 << endl;
		sleep(1); // sleep to allow seed to change
	}


Sample output of the code above:
124
47
96
145
68
117
40
89
138
61
110
33
82
131
54
103
152
75
124
47

The code below seems to work well, but I want to understand what's going on with the code above.

1
2
3
4
5
6
7
8
9
        int vi;
	int i;  // intialize debug loop
	for (i = 0; i < 20; i++) // debug loop
	{
		srand(time(0)); // initialize seed
		v1 = 33 + (rand() % (126 - 33 + 1));
		cout << v1 << endl;
		sleep(1); // sleep to allow seed to change
	}


Follow up question:
Is there a faster way to change the seed than sleeping for 1 second?

Thanks for your time.
dtv
The expected range here rand() % 126 + 33; is 33 to 158, that is 33 + (0 to 125).

Is there a faster way to change the seed than sleeping for 1 second

There is no need to repeatedly change the seed. Just call srand(time(0)); once at the start of your program (in main(), probably).
Thanks.

1st I changed the code to this:

1
2
3

v1 = rand() % 93 + 33;


The result was that I never got 126. Then I changed the code to this:

1
2
3

v1 = rand() % 94 + 33;


and got results in the 33 to 126 range.

so... 33 + (0 to 93) is 33 to 126. My mistake stemmed from not understanding that the rand() is adding the two integers together to make the range. Rookie mistake to be sure.

Also I removed sleep(1); , and moved srand(time(0)); up in scope to main. This results much faster pseudo random results.

Thanks for the help.
Just a short comment. The rand() function is not adding the two integers as you said.

the range() function is just giving you a random number, uniformly distributed on the interval 0 - RAND_MAX.

So, when you call it you get one number in this range. But then, with this number you compute another number with the modulo operation:

rand() % 94

which gives you a random number on the interval 0 - 93, to which you add 33.

@ aleonard:

Thank you for the clarification.

When I run this code to learn a bit more about the rand() function:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

using namespace std;

int main()
{	
	cout << "RAND_MAX = " << RAND_MAX << endl;
	cout << "rand() = " << rand() << endl;
	cout << "randl() % 100 = " << rand() % 100 << endl;
	cout << endl;
}


Here's what is returned:
1
2
3
RAND_MAX = 2147483647
rand() = 16807
randl() % 100 = 49


Is rand() % 100 finding the modular inverse of 16807 (mod 100) to arrive at 49?

Thanks,
dtv
Last edited on
Topic archived. No new replies allowed.